I’ve been trying to make it impossible to have two checkboxes checked at the same time in WPF but still allowing them both to be unchecked.
Does anyone know how I can achieve this?
This is what I have at the moment. Unfortunately this has the behaviour that both triggers are called when a checkbox is checked.
<Window.Resources>
<Style x:Key="style1" TargetType="{x:Type CheckBox}">
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=checkBox2, Path=IsChecked}" Value="True">
<Setter Property="CheckBox.IsChecked" Value="False"/>
</DataTrigger>
</Style.Triggers>
</Style>
<Style x:Key="style2" TargetType="{x:Type CheckBox}">
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=checkBox1, Path=IsChecked}" Value="True">
<Setter Property="CheckBox.IsChecked" Value="False"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Window.Resources>
<Grid>
<CheckBox Style="{StaticResource style1}" Name="checkBox1" Content="Check Box 1" />
<CheckBox Style="{StaticResource style2}" Name="checkBox2" Content="Check Box 2" />
</Grid>
Leverage
ListBox‘s exclusive singleSelectionModefor this…So for “n” mututally exclusive checkboxes simply add those many number of strings to the
x:Arrayabove. The above functionality works great fo radioboxes too.As you have said, the checkboxes will allow none or only one checked. And then to access which one is actually checked,
MyListBox.SelectedIndexwill help you.