Monday, December 26, 2011

WPF - Toggle Button


Toggle button is similar to checkbox control that holds its state when it clicked.  When Toggle button clicked first time it will set IsChecked property to true and on click again it will set IsChecked property to false. Toggle button also fires Checked event when IsChecked property set to true and UnChecked event when set to false. Toggle button is available in System.Windows.Controls.Premitives namespace.

Toggle Button also implements IsThreeState property. If IsThreeState property is enabled, the first click sets IsChecked property to true, the second click sets it to null and the third click sets it to false. 

Let’s have a look on below example.

<Window.Resources>
    <Style TargetType="{x:Type ToggleButton}"
           x:Key="toggleButtonStyle">
        <Setter Property="FontWeight" Value="Bold" />
        <Style.Triggers>
            <Trigger Property="IsChecked" Value="True">
                <Setter Property="Content" Value="IsChecked='True'" />
                <Setter Property="Foreground" Value="Green" />
            </Trigger>
            <Trigger Property="IsChecked" Value="False">
                <Setter Property="Content" Value="IsChecked='False'" />
                <Setter Property="Foreground" Value="Red" />
            </Trigger>
            <Trigger Property="IsChecked" Value="{x:Null}">
                <Setter Property="Content" Value="IsChecked='Null'" />
                <Setter Property="Foreground" Value="Blue" />
            </Trigger>
        </Style.Triggers>
    </Style>
</Window.Resources>
<Grid>
    <ToggleButton IsChecked="True"
                    IsThreeState="True"
                    Height="30" Width="150"
                    Style="{StaticResource toggleButtonStyle}">
    </ToggleButton>
</Grid>

IsChecked property set to true when application starts, and text color of Toggle Button appears as ‘green’.



On toggle button click, IsChecked property set to null and text color changes to ‘blue’.


Again click on toggle button, IsChecked property set to false and text color changes to  ‘red’.




See Also – 


2 comments: