In WPF, how can I prevent overriding my style?

Please do not get carried away in my example, just carry me for the sake of the question:

In my WPF application, if I wanted all the text fields to have a green background, I would easily set it as such in my applications. Resources.

<Style TargetType="TextBox"> <Setter Property="Background" Value="Green" /> </Style> 

This works PERFECTLY ... (thanks to WPF). However, if I had a TextBox somewhere in my application, that I wanted to add a little more styles to ... I LOSE my green background.

Example:

 <TextBox> <TextBox.Style> <Style> <Style.Triggers> <Trigger Property="TextBox.IsMouseOver" Value="True"> <Setter Property="TextBox.Foreground" Value="Red" /> </Trigger> </Style.Triggers> </Style> </TextBox.Style> </TextBox> 

In case the mouse is over, the TextBox will correctly have a red foreground, but the green background is completely lost.

So, the question is: How do I tell WPF NOT to completely erase all the styles that came from above, just because I have a simple, non-conflicting one, about such a small style added to the control somewhere?

+7
styling wpf
source share
1 answer

You can inherit already overridden styles using "BasedOn" in the style declaration.

In the ad for your second style, try the following:

 <TextBox> <TextBox.Style> <Style BasedOn="{StaticResource {x:Type TextBox}}"> <Style.Triggers> <Trigger Property="TextBox.IsMouseOver" Value="True"> <Setter Property="TextBox.Foreground" Value="Red" /> </Trigger> </Style.Triggers> </Style> </TextBox.Style> </TextBox> 

You can also create a style in the named style,

 <Style x:Key=MyNamedStyle> </Style> <Style BasedOn="{StaticResource MyNamedStyle}" > </Style> 
+11
source share

All Articles