谢谢@ 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}">
<!-- Some setters -->
</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>
这是因为前两个Buttons
使用款式DefaultButtonStyle
从ButtonResourceDictionary.xaml
,但另外三种Buttons
使用款式CustomButtonStyle
来自CustomButtonResourceDictionary.xaml
,它在其代码中合并ButtonResourceDictionary.xaml
。
我想这是很容易测试,但我有问题,以了解确切的情况。你的意思是与资源字典或什么的另一个程序集? – Sinatr
@ mm8我编辑了第1点,使其更容易理解,谢谢指出我的错误 –
@Sinatr问题是我不知道如何测试它,因为'ResourceDictionary'没有后面的代码,所以我可以'在那里放置一个断点。这个场景是:'StyleAssembly'是一个'ClassLibrary',它有'ResourceDictionary'叫'ButtonStyles',它有'CustomButtonStyle'。我的应用引用'StyleAssembly'并将其合并到App.xaml中,并且我的MainWindow具有20个'Buttons'使用样式'CustomButtonStyle'。它会让我的应用程序创建20个'ButtonStyles'实例吗? –