我找到了 this post关于提高网络上 ResourceDictionaries
的性能,但问题是它已经很老了(2011 年)。我正在考虑实现类似的东西,但我想知道 Microsoft 是否没有在 .NET Framework 的最新版本中修复此问题。关于这个话题我有几个问题,我希望这里有人能给出答案:
- .NET Framework 4.6.1 是否仍在通过创建多个实例来管理
ResourceDictionaries
,每次将它们分配给一个控件时一个实例? - 当我的
ResourceDictionary
中有例如样式"CustomButtonStyle"
调用"ButtonStyles"
在名为“StylesAssembly”
,然后在应用程序的App.xaml
中引用,该应用程序有 20 个Buttons
,CustomButtonStyle
分配给他们? - 我的理解是否正确,在上面的例子中,将有 20 个
"ButtonStyles"
ResourceDictionary
实例?
最佳答案
感谢@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
使用 ButtonResourceDictionary.xaml
中的样式 DefaultButtonStyle
,而另外三个 Buttons
使用样式 CustomButtonStyle
来自 CustomButtonResourceDictionary.xaml
,在其代码中合并了 ButtonResourceDictionary.xaml
。
关于c# - 同一个 ResourceDictionary 的多个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46808659/