Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the background color of a toggle button when the toggle button is checked

Tags:

wpf

xaml

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?

like image 896
vivek TP Avatar asked Apr 11 '11 08:04

vivek TP


2 Answers

<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.

like image 131
benba Avatar answered Sep 23 '22 06:09

benba


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

like image 24
Bruno Avatar answered Sep 20 '22 06:09

Bruno