Using BasedOn property with a Style defined in a different dictionary

╄→尐↘猪︶ㄣ 提交于 2019-12-06 04:23:29

问题


The application I'm working on has 2 ResourceDictionary, DefaultStyles.xaml and CustomStyles.xaml.

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:

Cannot find a Resource with the Name/Key TextBlockDefaultStyle.

It works well if both styles are in the same file.


回答1:


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>


来源:https://stackoverflow.com/questions/4649626/using-basedon-property-with-a-style-defined-in-a-different-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!