Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Mutually exclusive WPF checkboxes
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<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>
</Window>
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;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.