Reputation: 797
Recently I read about styles and control templates. As it says control templates are responsible for whole control design. But, I want for example to change only SPECIFIC part of the default control template, for example when mouse is over, or control has focus, when I wrote this:
<Style x:Key="StyleTextBox" TargetType="TextBox">
<Setter Property="Margin" Value="5, 0"/>
<Setter Property="VerticalContentAlignment" Value="Center"/>
<Setter Property="HorizontalContentAlignment" Value="Left"/>
<Setter Property="BorderBrush" Value="Black"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="SelectionBrush" Value="#CCFBE6D9"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="BorderBrush" Value="Black" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
..whole template got overridden... and its kinda not cool...
So how to change only isMouseOver visual style, without overriding the whole default style?
Upvotes: 0
Views: 70
Reputation: 25623
The whole template got replaced because your XAML says, "set the Template
to this ControlTemplate
that I'm declaring right here." Problem is, your template is empty. Use a template when you want to tell WPF, "represent the control using this visual tree". You gave it an empty visual tree and got exactly what you asked for ;).
In this case, however, your intention isn't to change the visual structure of the control; you just want to change a property. You can still use a Trigger
and Setter
for this, but you need not create a template to do so. A Style
has its own collection of triggers, so you can just move it there:
<Style x:Key="StyleTextBox" TargetType="TextBox">
<Setter Property="Margin" Value="5, 0"/>
<Setter Property="VerticalContentAlignment" Value="Center"/>
<Setter Property="HorizontalContentAlignment" Value="Left"/>
<Setter Property="BorderBrush" Value="Black"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="SelectionBrush" Value="#CCFBE6D9"/>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="BorderBrush" Value="Black" />
</Trigger>
</Style.Triggers>
</Style>
This works because you're just changing a property of the styled control; generally, you can expect templates to honor the top-level properties of the controls to which the template is applied. For example, the default TextBox template should ensure that the TextBox is drawn with a background conforming to the templated parent's Background
property.
Triggers on templates are more useful in cases where you want to manipulate a specific sub-element declared within a custom template.
Upvotes: 2