#353 – Binding a Three-State CheckBox to a Nullable Bool

Because a three-state CheckBox can take on any one of three different values, its current value can’t be represented by a simple bool.  A bool can only take on true and false values.

A three-state CheckBox can instead be bound to a nullable bool (represented by bool?), which can take on three different values.

  • true  (checked)
  • false  (not checked)
  • null  (indeterminate)

In the example below, we bind a CheckBox control’s IsChecked property to a nullable bool property.

        <CheckBox Content="Happy" IsChecked="{Binding IsHappy}" IsThreeState="True"/>

In the code-behind, we define the property and set the main window’s data context.

        // Nullable bool - can be true, false or null
        public bool? IsHappy { get; set; }

		public MainWindow()
		{
			this.InitializeComponent();
            this.DataContext = this;
        }
Follow

Get every new post delivered to your Inbox.

Join 355 other followers