I want to change the background color of a toggle button when the toggle button is checked and vice versa.
How can I achieve that?
<ToggleButton Content="toggle"> <ToggleButton.Style> <Style TargetType="{x:Type ToggleButton}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="ToggleButton"> <Border BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}"> <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/> </Border> </ControlTemplate> </Setter.Value> </Setter> <Style.Triggers> <Trigger Property="IsChecked" Value="True"> <Setter Property="Background" Value="Red" /> </Trigger> </Style.Triggers> </Style> </ToggleButton.Style> </ToggleButton>
Nearly the same as Klaus ones, but using "TemplateBinding" instead of "TargetName". With the TemplateBinding, the ControlTemplate use the BorderBrush and Background from the ToggleButtons DefaultStyle. So the Trigger can set the ToggleButtons Background and with the Border this one will also be shown.
The best simple way to acheive this (and without any Blend and overriding 50 lines of XAML ;) is this way, i.e. using triggers :
<Window x:Class="StackOverflow.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300"> <Grid> <ToggleButton x:Name="tg" Height="20" Width="80"> <ToggleButton.Style> <Style TargetType="{x:Type ToggleButton}"> <Setter Property="Background" Value="Green"/> <Style.Triggers> <Trigger Property="IsChecked" Value="true"> <Setter Property="Background" Value="Red"/> </Trigger> </Style.Triggers> </Style> </ToggleButton.Style> </ToggleButton> </Grid>
Try this in the first place before going any further and see if it suit your needs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With