WPF ToggleButton


The WPF ToggleButton is a “sticky” button that holds its state when it is clicked. Clicking it the first time sets its IsChecked property to true and clicking it again sets its IsChecked property to false. The default appearance of a ToggleButton is the same as the Button and RepeatButton.

One use-case for a toggle button is for the Toolbar. Perhaps your app needs to be on top of all other windows. You could create a toggle button that has two events.

Below is the XAML.

<Window x:Class="AlwaysOnTop.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:AlwaysOnTop"
        mc:Ignorable="d"
        WindowStartupLocation="CenterScreen"
        Topmost="False"
        Title="AlwaysOnTop" Height="250" Width="400">
    <StackPanel Margin ="4">
        <ToolBar>
            <Label>Hello!</Label>
            <Separator/>
            <ToggleButton Name="tgbtn" Checked="tgbtn_Checked" Unchecked="tgbtn_Unchecked">On Top</ToggleButton>
        </ToolBar>
        <TextBlock TextWrapping="Wrap">This illustrates the setting for the window called <Span FontWeight="Bold">Topmost.</Span>
        We have a ToolBar above that has a ToggleButton in it. For the ToggleButton I have added two
            events: Checked and Unchecked. In the code behind I need to set the Topmost property of the
            main window. How do I do that? Here is the line of code that makes this app sit on top: 
            <Span FontWeight="Bold">Application.Current.MainWindow.Topmost = true;</Span> This line is inside the
            Checked event. Set it to false inside the Unchecked event.
        </TextBlock>
    </StackPanel>
</Window>

Below is the code behind.

using System.Windows;

namespace AlwaysOnTop
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        private void tgbtn_Checked(object sender, RoutedEventArgs e)
        {
            Application.Current.MainWindow.Topmost = true;
        }
        private void tgbtn_Unchecked(object sender, RoutedEventArgs e)
        {
            Application.Current.MainWindow.Topmost = false;
        }
    }
}