使用具有在不同字典中定义的样式的 BasedOn 属性 [英] Using BasedOn property with a Style defined in a different dictionary
问题描述
我正在处理的应用程序有 2 个 ResourceDictionary、DefaultStyles.xaml 和 CustomStyles.xaml.
The application I'm working on has 2 ResourceDictionary, DefaultStyles.xaml and CustomStyles.xaml.
CustomStyles 字典中的样式是否可能使用其他字典中定义的基本样式?
Is it possible that a style in the CustomStyles dictionary uses a base style defined in the other dictionary?
DefaultStyles.xaml:
<Style x:Key="TextBlockDefaultStyle" TargetType="TextBlock">
<Setter Property="Margin" Value="4" />
</Style>
CustomStyles.xaml:
<Style x:Key="SectionTitleStyle" TargetType="TextBlock" BasedOn="{StaticResource TextBlockDefaultStyle}">
<Setter Property="FontSize" Value="16" />
</Style>
App.xaml:
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Assets/Styles/DefaultStyles.xaml"/>
<ResourceDictionary Source="Assets/Styles/CustomStyles.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
代码运行时,抛出如下异常:
When the code runs, the following exception is thrown:
找不到名称/键为 TextBlockDefaultStyle 的资源.
Cannot find a Resource with the Name/Key TextBlockDefaultStyle.
如果两种样式都在同一个文件中,效果会很好.
It works well if both styles are in the same file.
推荐答案
需要直接引用其他样式的字典.
You need to reference the dictionary with the other style directly.
CustomStyles.xaml:
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="DefaultStyles.xaml" />
</ResourceDictionary.MergedDictionaries>
<Style x:Key="SectionTitleStyle" TargetType="TextBlock" BasedOn="{StaticResource TextBlockDefaultStyle}">
<Setter Property="FontSize" Value="16" />
</Style>
这篇关于使用具有在不同字典中定义的样式的 BasedOn 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!