用户控件中的资源字典

3
我有一个用户控件,它使用资源字典。在这个用户控件中,还有另一个使用相同资源字典的用户控件。我想知道的是WPF是否真正加载了两次,如果是,是否会对性能造成影响。有没有更好的方法来解决这个问题。
提前感谢。
1个回答

1

有趣的问题。我很好奇,于是进行了调查。看起来WPF为每个元素的出现加载一个新的ResourceDirectionary(以及定义和使用该字典中的所有资源)。

请看下面的代码:

ViewModel:

public class Person
{
    public string name { get; set; }
    public int age { get; set; }
    public Person() { }
}

资源(Dictionary1.xaml):

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:so="clr-namespace:SO"
    >
    <so:Person x:Key="m" name="Methuselah" age="969" />
</ResourceDictionary>

视图:

<Window
    x:Class="SO.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:so="clr-namespace:SO"
    Height="200" Width="300"
    Title="SO Sample"
    >
    <Window.Resources>
        <ResourceDictionary Source="Dictionary1.xaml" />
    </Window.Resources>

    <StackPanel DataContext={StaticResource m}>
        <UserControl>
            <UserControl.Resources>
                <ResourceDictionary Source="Dictionary1.xaml" />
            </UserControl.Resources>
            <TextBlock x:Name="inner" DataContext="{StaticResource m}" Text="{Binding Path=name}" />
        </UserControl>        
        <TextBlock x:Name="outer" Text="{Binding Path=name}" />        
        <Button Click="Button_Click">Change</Button>        
    </StackPanel>
</Window>

在 Person() 构造函数处设置断点,注意对象被实例化了两次。或者让 Person 实现 INotifyPropertyChange,并为 Button_Click 添加以下代码:
private void Button_Click( object sender, RoutedEventArgs e ) {
    Person innerPerson = this.inner.DataContext as Person;
    Person outerPerson = this.outer.DataContext as Person;
    innerPerson.name = "inner person";
    outerPerson.name = "outer person";
}

如果您想要每个资源只有一个实例,请将这些资源放在 app.xaml 文件的 元素中。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接