How to base a style on another style in a resource dictionary?

后端 未结 3 1829
时光取名叫无心
时光取名叫无心 2020-12-25 12:27

I have a theme that is applied to all buttons in a resource dictionary. Now I want to add a trigger to the button while inheriting the style changes from the dictionary. I t

相关标签:
3条回答
  • 2020-12-25 13:08

    I think there is no base style defined for "control" so your BasedOn="{StaticResource {x:Type Control}}" part won't find anything.

    You probably want to change

    <Style x:Key="ValidTrigger" TargetType="Control" BasedOn="{StaticResource {x:Type Control}}" >
    

    to

    <Style x:Key="ValidTrigger" TargetType="Button" BasedOn="{StaticResource {x:Type Button}}" >
    
    0 讨论(0)
  • 2020-12-25 13:15

    One trick I've used in the past: in your ResourceDictionary that defines blanket styles for your application, add an x:Key to the style you'd like to inherit from, like so:

    <Style TargetType="{x:Type Button}" x:Key="ButtonStyle">
      <!-- your style here -->
    </Style>
    

    To apply this style to all controls of the specified type (Button in this example) without having to explicitly set the Style attribute of every Button, add another style that's BasedOn this style, but doesn't have a key:

    <Style TargetType="{x:Type Button}" BasedOn="{StaticResource ButtonStyle}" />
    

    Using this method, all Buttons in your application will automatically inherit your custom style, but you can still create additional styles BasedOn the ButtonStyle entry and avoid blowing away all of your custom styling.

    0 讨论(0)
  • 2020-12-25 13:32

    Give your base Style a name, say FooStyle.

    In the example you gave, modify the TargetType and BasedOn to look as follows:

     <Style x:Key="ValidTrigger" 
            TargetType="{x:Type Control}" BasedOn="{StaticResource {x:Type Control}}" >
        <Style.Triggers>
            <DataTrigger Binding="{Binding Path=IsValid}" Value="False">
                <Setter Property="IsEnabled" Value="false" />
            </DataTrigger>
        </Style.Triggers>
    </Style>
    
    0 讨论(0)
提交回复
热议问题