I am trying to change the hovering color of a toggle button when the button is checked. For some reason, it doesn't work. However, I can change the thickness of the border.
<!--App.xaml-->
<ResourceDictionary>
<Style x:Key="MyStyle" TargetType="{x:Type ToggleButton}">
<Style.Triggers>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="IsChecked" Value="True"/>
<Condition Property="IsMouseOver" Value="True"/>
</MultiTrigger.Conditions>
<Setter Property="BorderThickness" Value="10"/> <!--works-->
<Setter Property="BorderBrush" Value="Red"/> <!--fails-->
<Setter Property="Background" Value="Red"/> <!--fails-->
</MultiTrigger>
</Style.Triggers>
</Style>
</ResourceDictionary>
<!--MainWindow.xaml-->
<Grid>
<ToggleButton
Style="{StaticResource MyStyle}"
Content="Button"
HorizontalAlignment="Left"
Margin="271,0,0,0"
VerticalAlignment="Center"
Height="108"
Width="192"
/>
</Grid>
CodePudding user response:
That's because ToggleButton has a ControlTemplate that defines its visual structure - and this template has precedence over style setters. The template uses a Border element with x:Name Border to render the ToggleButton's border, and a Grid named ContentPresenter to host the button's content. The template also defines triggers that modify the Border's properties when the button is in the MouseOver state - and these have a higher precedence than style triggers. To override this behavior, you need to use template bindings in your style:
<Style x:Key="MyStyle" TargetType="ToggleButton">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ToggleButton">
<Border x:Name="Border"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
...
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="IsChecked" Value="True"/>
<Condition Property="IsMouseOver" Value="True"/>
</MultiTrigger.Conditions>
<Setter Property="BorderBrush" Value="Red"/>
<Setter Property="BorderThickness" Value="10"/>
</MultiTrigger>
</Style.Triggers>
</Style>
Now the style setters will update the properties of the Border element defined in the template, overriding the default hover behavior. Note that you should also include template bindings for all the other properties you want to be styled (Background, Foreground etc.).