现在是实际问题。我试图摆脱合并字典,但是失败了。我理解使用StaticResource时查找需要在当前资源之前定义资源。我制作了以下简短的示例:
一个主项目和一个自定义控件库。
该自定义控件库包含2个XAML文件。
<!-- Colors.xaml -->
<ResourceDictionary [stripped namespaces] >
<SolidColorBrush x:Key="myColor" Color="Green"/>
</ResourceDictionary>
<!-- Templates.xaml -->
<ResourceDictionary [stripped namespaces]>
<ControlTemplate x:Key="myTemplate" TargetType="Button">
<Rectangle Fill="{StaticResource myColor}"/>
</ControlTemplate>
</ResourceDictionary>
现在在主项目中,MainWindow.xaml 看起来像这样
<Window x:Class="ResourceTest.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/ResourceTestLib;component/Themes/Colors.xaml"/>
<ResourceDictionary Source="/ResourceTestLib;component/Themes/Template.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
<Grid>
<Button Template="{StaticResource myTemplate}"/>
</Grid>
</Window>
这是我们期望的目标,但不幸的是,由于找不到资源“ myColor”,所以程序崩溃了。当然,我知道如何解决它——在Templates.xaml中添加MergedDictionary并引用Colors.xaml。但我一直认为(其实从来没有仔细查过)资源是根据逻辑树和元素资源进行查找的。我的理解是:创建按钮,尝试查找模板......找到;尝试查找颜色,在自己的资源中未找到,向上搜索并使用窗口资源。
看起来我错了。因此,希望有人能给我一些提示。我们在 WPF 中大量使用,尽管如此,由于一些最初错误的行为,我们的性能非常糟糕,只是因为资源查找。
非常感谢您的帮助。 谢谢 Nico
DynamicResource
替代StaticResource
来设置MyColor
有什么问题吗?最后我检查过,性能差异不足以证明不使用动态资源。 - RachelColors.xaml
或Templates.xaml
的引用。通常我会将通用资源(颜色、模板、样式等)加载到Application.Resources
中,而像DataTemplates这样的特定资源则会被加载到使用它们的UserControl中。 - Rachel