Home > Blockchain >  WPF - Uncheck every other boxes when a box is checked
WPF - Uncheck every other boxes when a box is checked

Time:09-14

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!

CodePudding user response:

Suppose you have something like this in .xaml

<CheckBox Content="CB1" IsChecked="{Binding IsCb1Checked}" />
<!-- Some other controls and panels -->
<CheckBox Content="CB2" IsChecked="{Binding IsCb2Checked}" />
<!-- Some other controls and panels -->
<CheckBox Content="CB3" IsChecked="{Binding IsCb3Checked}" />

You can do a small trick in the setters of the boolean properties, keep in mind that you won't update the status of the other checkboxes if the user uncheck the checked CheckBox

private bool _isCb1Checked;

public bool IsCb1Checked
{
    set
    {
        if (_isCb1Checked == value) return;
        _isCb1Checked = value;
        OnPropertyChanged();
        if (value)
            UpdateCheckBoxStatus(nameof(IsCb1Checked));
    }
    get => _isCb1Checked;
}

private bool _isCb2Checked;

public bool IsCb2Checked
{
    set
    {
        if (_isCb2Checked == value) return;
        _isCb2Checked = value;
        OnPropertyChanged();
        if (value)
            UpdateCheckBoxStatus(nameof(IsCb2Checked));
    }
    get => _isCb2Checked;
}

private bool _isCb3Checked;

public bool IsCb3Checked
{
    set
    {
        if (_isCb3Checked == value) return;
        _isCb3Checked = value;
        OnPropertyChanged();
        if (value)
            UpdateCheckBoxStatus(nameof(IsCb3Checked));
    }
    get => _isCb3Checked;
}

private void UpdateCheckBoxStatus(string propertyName)
{
    IsCb1Checked = propertyName == nameof(IsCb1Checked);
    IsCb2Checked = propertyName == nameof(IsCb2Checked);
    IsCb3Checked = propertyName == nameof(IsCb3Checked);
}

In action..

enter image description here

CodePudding user response:

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);
}
  • Related