2012-03-05 91 views
3

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

在此先感谢。

回答

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> 

放了Pers。断点on()构造函数,并注意对象被实例化两次。或者,使个人实现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。