感谢 @mm8 发布的答案。它是100%正确的,但我想发布自己的答案,因为我发现了一些有趣的东西,可以对他人有用。
答案是:如果应用程序引用了 ResourceDictionary 实例(无论有多少控件使用其样式),则只会创建一次,但是每次在另一个也在应用程序中使用的 ResourceDictionary 中引用它时,都会重新实例化。
因此,为了给您举例说明这种情况,假设我们有以下结构:
- StylesAssembly.dll
- ButtonResourceDictionary.xaml
- CustomButtonResourceDictionary.xaml
- Application.exe
- App.xaml
- MainWindow.xaml
ButtonResourceDictionary.xaml包含以下代码:
<Style x:Key="DefaultButtonStyle" TargetType="{x:Type Button}">
<!
</Style>
CustomButtonResourceDictionary.xaml有以下代码,其中使用了ButtonResourceDictionary.xaml
:
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="ButtonResourceDictionary.xaml" />
</ResourceDictionary.MergedDictionaries>
<Style x:Key="CustomButtonStyle" TargetType="{x:Type Button}" BasedOn="{StaticResource DefaultButtonStyle}">
<!-- Some setters -->
</Style>
Application.exe
引用了 StylesAssembly.dll
,App.xaml 中有以下代码:
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/StylesAssembly;component/ButtonResourceDictionary.xaml" />
<ResourceDictionary Source="pack://application:,,,/StylesAssembly;component/CustomButtonResourceDictionary.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
现在,如果我们的
MainWindow.xaml 中有以下内容,那么
ButtonResourceDictionary.xaml
将只有
一个实例:
<StackPanel>
<Button Style="{StaticResource DefaultButtonStyle}" />
<Button Style="{StaticResource DefaultButtonStyle}" />
<Button Style="{StaticResource DefaultButtonStyle}" />
<Button Style="{StaticResource DefaultButtonStyle}" />
<Button Style="{StaticResource DefaultButtonStyle}" />
</StackPanel>
但是如果我们的MainWindow.xaml中有类似这样的内容,CustomButtonResourceDictionary.xaml
将会有一个实例,但是ButtonResourceDictionary.xaml
将会有两个实例:
<StackPanel>
<Button Style="{StaticResource DefaultButtonStyle}" />
<Button Style="{StaticResource DefaultButtonStyle}" />
<Button Style="{StaticResource CustomButtonStyle}" />
<Button Style="{StaticResource CustomButtonStyle}" />
<Button Style="{StaticResource CustomButtonStyle}" />
</StackPanel>
这是因为前两个使用了ButtonResourceDictionary.xaml
中的DefaultButtonStyle
样式,而另外三个使用了来自CustomButtonResourceDictionary.xaml
的CustomButtonStyle
样式,后者在其代码中合并了ButtonResourceDictionary.xaml
。
ResourceDictionary
没有代码后端,所以我无法在那里设置断点。情况是这样的:StyleAssembly
是一个ClassLibrary
,其中包含名为ButtonStyles
的ResourceDictionary
,里面有CustomButtonStyle
。我的应用程序引用了StyleAssembly
并将其合并到了App.xaml中,我的MainWindow有20个使用CustomButtonStyle
样式的按钮。这会导致我的应用程序创建20个ButtonStyles
实例吗? - Kacper StachowskiUserControl.Resources
中编写<ResourceDictionary Source="pack://application:,,,/ClassLibrary;component/ResourceDictionary.xaml" />
。这确实会为每个此类用户控件的实例创建一个新的资源字典实例。相反,您必须每个应用程序定义它一次。 - Sinatr