Toggle Button act as a base class for controls that can switch states, such as CheckBox and RadioButton. It is a button that is mainly used for switching states. It is possible to have a three state also. It will check the IsChecked property to verify selected or not.
Step 1: Open a blank app and add a ToggleButton control either from the toolbox or by copying the following XAML code into your grid.
- <TextBlock Text="Toggle Button" FontSize="20"></TextBlock>
- <StackPanel Margin="10,40,0,0">
- <StackPanel Orientation="Horizontal">
- <TextBlock Text="Toggle Button" VerticalAlignment="Center" FontSize="20"></TextBlock>
- <ToggleButton Name="myToggleButton" Content="OFF" Margin="15,0,0,0" Width="150" Height="50" Click="myToggleButton_Click"> </ToggleButton>
- </StackPanel>
- </StackPanel>
Step 2: Copy and paste the following code to the cs page to handle the events generated on checking and unchecking.
- private void myToggleButton_Click(object sender, RoutedEventArgs e)
- {
- if(myToggleButton.IsChecked == true)
- {
- myToggleButton.Content = "ON";
- }
- else
- {
- myToggleButton.Content = "OFF";
- }
- }
Here we are changing the content of the button accordingly on clicking.
Step 3: Run your application and test yourself.