Mutually Exclusive WPF Checkboxes

using System.Windows;
using System.Windows.Controls.Primitives;
using System.Windows.Interactivity;

public class UncheckOnSignalBehavior : Behavior<ToggleButton>
{
    public static readonly DependencyProperty SignalProperty = DependencyProperty.Register(
        "Signal",
        typeof(bool),
        typeof(UncheckOnSignalBehavior),
        new PropertyMetadata(SignalProperty_PropertyChanged));

    private static void SignalProperty_PropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        ((UncheckOnSignalBehavior)sender).Update();
    }

    public bool Signal
    {
        get { return (bool)GetValue(SignalProperty); }
        set { SetValue(SignalProperty, value); }
    }

    protected override void OnAttached()
    {
        Update();
    }

    private void Update()
    {
        if (AssociatedObject != null && Signal)
        {
            AssociatedObject.IsChecked = false;
        }
    }
}

Usage:

<CheckBox IsChecked="{Binding A}">
    <i:Interaction.Behaviors>
        <local:UncheckOnSignalBehavior Signal="{Binding None}" />
    </i:Interaction.Behaviors>
    Option A
</CheckBox>
<CheckBox IsChecked="{Binding B}">
    <i:Interaction.Behaviors>
        <local:UncheckOnSignalBehavior Signal="{Binding None}" />
    </i:Interaction.Behaviors>
    Option B
</CheckBox>
<CheckBox IsChecked="{Binding C}">
    <i:Interaction.Behaviors>
        <local:UncheckOnSignalBehavior Signal="{Binding None}" />
    </i:Interaction.Behaviors>
    Option C
</CheckBox>
<CheckBox IsChecked="{Binding None}">
    <i:Interaction.Behaviors>
        <local:UncheckOnSignalBehavior Signal="{Binding A}" />
        <local:UncheckOnSignalBehavior Signal="{Binding B}" />
        <local:UncheckOnSignalBehavior Signal="{Binding C}" />
    </i:Interaction.Behaviors>
    None of the above
</CheckBox>

Leave a Reply

Your email address will not be published.