2
votes

I have some locally defined styles within Window.Resources. I have some styles for a TextBlock, TextBox, CheckBox and RadioButton. These are supposed to be applied to all controls in the window, so I haven't provided a value for x:Key. I would like them to inherit from a style targeting FrameworkElement. So I have something like:

<Style TargetType="{x:Type RadioButton}">
    ...
</Style>

<Style TargetType="{x:Type TextBlock}">
   ...
</Style>

<Style TargetType="{x:Type TextBox}">
    ...
</Style>

<Style TargetType="{x:Type CheckBox}">
    ...
</Style>

<Style x:Key="TriggerBase" TargetType="{x:Type FrameworkElement}">
    <Style.Triggers>                
        <Trigger Property="UIElement.IsMouseOver" Value="True">
            ...
        </Trigger>                
    </Style.Triggers>
</Style>

My problem is that I am unable to set the BasedOn property to inherit from my TriggerBase style. After looking at similar questions, such as this and this, I still cannot get it working. These answers suggest you need to specify the TargetType on your base style, which I have done.

I thought maybe the Styles have to target the exact same type, but after digging around on MSDN I found that wasn't the problem:

If you create a style with a TargetType property and base it on another style that also defines a TargetType property, the target type of the derived style must be the same as or be derived from the type of the base style.

If I set BasedOn like BasedOn="{DynamicResource TriggerBase}", it can find my TriggerBase, but I get an error stating:

A 'DynamicResourceExtension' cannot be set on the 'BasedOn' property of type 'Style'. A 'DynamicResourceExtension' can only be set on a DependencyProperty of a DependencyObject.

If I try BasedOn="{StaticResource TriggerBase}", I get an error that it cannot find TriggerBase. One of the linked answers above showed using StaticResource like BasedOn="{StaticResource {x:Type FrameworkElement}, but it still cannot resolve the style.

How can I inherit from the TriggerBase style? I'm targeting .NET 4.5.

1
Just tried your code and the only thing I had to do is move TriggerBase style to the top and then BasedOn="{StaticResource TriggerBase}" workeddkozl
That worked, thanks. I didn't realise the ordering was important. Lesson learned. I'll accept your answer if you want to add it as one.Darren Hale

1 Answers

3
votes

You are correct and you can base your styles on FrameworkElement style just need to move

<Style x:Key="TriggerBase" TargetType="{x:Type FrameworkElement}">

</Style>

to the top and then

<Style TargetType="{x:Type RadioButton}" BasedOn="{StaticResource TriggerBase}">

will work