#360 – Binding a ToggleButton’s IsChecked Property to a Boolean Variable

Instead of handling the Checked and Unchecked events of a ToggleButton and then setting a boolean variable to represent the current state, you’ll most often just use data binding to bind the IsChecked property to a boolean variable.

In the example below, we have three ToggleButton controls, each bound to a boolean property.

        <StackPanel Orientation="Horizontal">
            <ToggleButton Content="Bold" IsChecked="{Binding Bold}"  FontWeight="Bold" Padding="5" />
            <ToggleButton Content="Italic" IsChecked="{Binding Italic}" FontStyle="Italic" Padding="5"/>
            <ToggleButton IsChecked="{Binding Underline}" Padding="5" >
        <Button Content="Test" Click="Button_Click" Margin="15" Padding="3"/>

In the code-behind, we define the boolean properties that we can bind to and then set the data context to refer to the parent class.

        public bool Bold { get; set; }
        public bool Italic { get; set; }
        public bool Underline { get; set; }

		public MainWindow()
            this.DataContext = this;

        private void Test_Click(object sender, RoutedEventArgs e)
            MessageBox.Show(string.Format("Bold: {0}, Italic: {1}, Underline: {2}", Bold, Italic, Underline));