I figured out a solution that doesn't resort to processing the checked states in code-behind, so I'm going to document it for posterity.
The first trick is to use RadioButton
instead, with and associated GroupName
. Radio buttons within the same group will automatically ensure that only one of them is checked at any given time, which avoids the issue with manually managing the checked states.
The second trick is to bind a CommandParameter
to the radio buttons DataContext
.
<RadioButton
Name="rdbSelected"
GroupName="itemsRadioGroup"
Command="{Binding
RelativeSource={RelativeSource AncestorType=UserControl},
Path=DataContext.SelectItemCommand}"
CommandParameter="{Binding
RelativeSource={RelativeSource Self},
Path=DataContext}"/>
The radio buttons command fires on every click, not just when it is checked, but we get away with this because unlike CheckBox
it is not possible to un-check a radio button, so double-clicking the radio button will only confirm the SelecedItem
.
If the SelectedItem
property fires a PropertyChanged
event, it may be advisable to have the command handler check whether it is in fact setting a new value, or just repeating the previous one:
RelayCommand<object> cmd = new RelayCommand<object>(
(o) =>
{
if (this.SelectedItem != o)
this.SelectedItem = o;
});