Search code examples
c#wpfdata-binding

WPF - Uncheck every other boxes when a box is checked


as the title suggests, I'm trying to find a way to do the following:
-I have multiple checkboxes in a xaml file (let's say 5). When any of these boxes is checked, I want every other box to automatically be unchecked.

While this isn't too hard in itself, I was wondering if there was a way to avoid the tedious process of creating 5 unique commands along with 5 unique booleans to be bound to my checkboxes.

Thanks a lot!


Solution

  • It really seems to me that what you actually want is a RadioButton, which natively does it.

    But just in case you really want a checkbox, you can do it like this:

    <StackPanel x:Name="container">
        <CheckBox Checked="CheckBox_Checked"/>
        <CheckBox Checked="CheckBox_Checked"/>
        <CheckBox Checked="CheckBox_Checked"/>
        <CheckBox Checked="CheckBox_Checked"/>
    </StackPanel>
    

    Code behind:

    private void CheckBox_Checked(object sender, RoutedEventArgs e)
    {
        foreach (var checkbox in container.Children.OfType<CheckBox>())
            checkbox.IsChecked = sender.Equals(checkbox);
    }