#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" >
                <TextBlock>
                    <Underline>Underline</Underline>
                </TextBlock>
            </ToggleButton>
        </StackPanel>
        <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.InitializeComponent();
            this.DataContext = this;
        }

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

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

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

  1. Pingback: Dew Drop – August 9, 2011 | Alvin Ashcraft's Morning Dew

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: