用户控件中的资源字典

时间:2012-03-05 04:11:04

标签: wpf xaml .net-4.0

我有一个用户控件,它使用资源字典。在该用户控件中,有另一个用户控件使用相同的资源字典。我想知道的是wpf是否实际加载了两次,如果是,是否有任何性能影响。有没有更好的方法来做到这一点。

提前致谢。

1 个答案:

答案 0 :(得分:1)

有趣的问题。我很有兴趣去调查。似乎WPF为每个元素外观加载一个新的ResourceDirectionary(以及定义的所有资源和使用的字典)。

看看以下代码:

视图模型:

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文件的元素中使用reousrces。