我有一个用户控件,它使用资源字典。在这个用户控件中,还有另一个使用相同资源字典的用户控件。我想知道的是WPF是否真正加载了两次,如果是,是否会对性能造成影响。有没有更好的方法来解决这个问题。
提前感谢。
提前感谢。
有趣的问题。我很好奇,于是进行了调查。看起来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>
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";
}