#355 – Implementing Three-State CheckBox Dependent Behavior

You can use a three-state CheckBox to reflect the state of a set of other CheckBox controls.

Here’s some sample code that implements this behavior.  (See the previous post for the XAML).

    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private bool doEat;
        public bool DoEat
        {
            get { return doEat; }
            set
            {
                doEat = value;
                OnPropertyChanged("DoEat");
                OnPropertyChanged("DoEverything");
            }
        }

        // Add same code for DoPray and DoLove properties here

        // Nullable bool - can be true, false or null
        public bool? DoEverything
        {
            get
            {
                if (DoEat && DoPray && DoLove)
                    return true;
                else if (!DoEat && !DoPray && !DoLove)
                    return false;
                else
                    return null;
            }

            set
            {
                if (value == true)
                    DoEat = DoPray = DoLove = true;
                else
                    DoEat = DoPray = DoLove = false;
            }
        }

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

        private void OnPropertyChanged(string prop)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(prop));
        }
    }

#354 – Use Three-State CheckBox to Show State of Other CheckBoxes

Three-state CheckBox controls are often used in conjunction with other CheckBox controls. The three-state CheckBox appears checked if all other checkboxes are checked, unchecked if nothing else is checked, or the indeterminate state if some other CheckBox controls are checked.

Here’s an example, starting with the XAML:

        <CheckBox Content="Do Everything" IsChecked="{Binding DoEverything}" IsThreeState="True"/>
        <CheckBox Content="Eat" IsChecked="{Binding DoEat}" Margin="20,0,0,0"/>
        <CheckBox Content="Pray" IsChecked="{Binding DoPray}" Margin="20,0,0,0"/>
        <CheckBox Content="Love" IsChecked="{Binding DoLove}" Margin="20,0,0,0"/>

At run-time, you want the following behavior:

  • User checks Do Everything, all other items become checked

  • User unchecks Do Everything, all other items become unchecked

  • User checks individual items, Do Everything becomes checked if everything else is checked, unchecked if nothing is checked, or indeterminate if at some items are checked

See post #355 for an example of the code-behind that implements this behavior.