使用带有在不同字典中定义的样式的BasedOn属性

Ale*_*x B 4 c# silverlight resourcedictionary mergeddictionaries

我正在处理的应用程序有2个ResourceDictionary,DefaultStyles.xaml和CustomStyles.xaml.

CustomStyles字典中的样式是否可能使用其他字典中定义的基本样式?

DefaultStyles.xaml:

<Style x:Key="TextBlockDefaultStyle" TargetType="TextBlock">  
    <Setter Property="Margin" Value="4" />  
</Style>  
Run Code Online (Sandbox Code Playgroud)

CustomStyles.xaml:

<Style x:Key="SectionTitleStyle" TargetType="TextBlock" BasedOn="{StaticResource TextBlockDefaultStyle}">
    <Setter Property="FontSize" Value="16" />
</Style>
Run Code Online (Sandbox Code Playgroud)

App.xaml中:

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Assets/Styles/DefaultStyles.xaml"/>
            <ResourceDictionary Source="Assets/Styles/CustomStyles.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>
Run Code Online (Sandbox Code Playgroud)

代码运行时,抛出以下异常:

找不到具有Name/Key TextBlockDefaultStyle的资源.

如果两个样式都在同一个文件中,它的效果很好.

Bry*_*tts 7

您需要直接使用其他样式引用字典.

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>
Run Code Online (Sandbox Code Playgroud)

  • 这种行为是合理的.但我只是遇到了另一个问题:在我用键而不是类型将其更改为引用之前,基于OnOn ="{StaticResource {x:Type Button}}"无效.这个看起来像WPF运行时中的bug. (2认同)