Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In WPF, how do I prevent my style from being overridden?

Tags:

styling

wpf

Please don't get caught up in my example, just bear with me for the sake of the question:

In my WPF application, if I wanted all TextBoxes to have a "green" background, I would easily set it as such in my Application.Resources.

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

This works PERFECTLY... (thank you WPF). However, if I had a TextBox somewhere in my application that I wanted to append a little more styling 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>

That TextBox will correctly have the red Foreground when the mouse is over, but the green Background is completely lost.

So, the question is: How do I tell WPF NOT to completely wipe out all styling that came from above just because I have a simple, non-conflicting, oh so tiny style added to a control somewhere?

like image 553
Timothy Khouri Avatar asked Oct 19 '09 13:10

Timothy Khouri


1 Answers

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

In the declaration for your second style, try this:

<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 base the style on a named style,

<Style x:Key=MyNamedStyle>
</Style>

<Style BasedOn="{StaticResource MyNamedStyle}" >
</Style>
like image 195
Guy Starbuck Avatar answered Oct 08 '22 16:10

Guy Starbuck