【问题标题】:Using BasedOn property with a Style defined in a different dictionary使用具有在不同字典中定义的 Style 的 BasedOn 属性
【发布时间】:2011-01-10 17:34:49
【问题描述】:

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

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

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>

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

找不到具有名称/键 TextBlockDefaultStyle 的资源。

如果两种样式在同一个文件中,效果会很好。

【问题讨论】:

    标签: c# silverlight resourcedictionary mergeddictionaries


    【解决方案1】:

    你需要直接引用其他样式的字典。

    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="{StaticResource {x:Type Button}}" 直到我将其更改为按键引用而不是类型引用。这个看起来像 WPF 运行时中的错误。
    • 根据@alehro 的评论,我通过将&lt;Style&gt;s 移动到窗口内的面板资源中来解决此问题。然后BasedOn="{StaticResource {x:Type Button}}" 工作了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多