I have the following scenario where a class like this:
public class PetOwnerViewModel{
public PetOwnerStatus Status{get{return _petOwner.Status;}}
public ICommand SetStatusCommand {get{...}}
}
Is DataContext to a group of RadioButtons similar to this:
<Parent DataContext="{Binding Path=PetOwner}" >
<Parent.Resources>
<myenums:PetOwnerStatus x:Key="CATLOVER">
CatLover
</myenums:PetOwnerStatus>
<myenums:PetOwnerStatus x:Key="DOGLOVER">
DogLover
</myenums:PetOwnerStatus>
</Parent.Resources>
<StackPanel>
<RadioButton Name="catLoverRadioButton"
Command="{Binding SetStatusCommand}"
CommandParameter="{StaticResource DOGLOVER}"
GroupName="PetOwnerStatusRadioButtonGroup">
Cat Lover
</RadioButton>
<RadioButton Name="dogLoverRadioButton"
Command="{Binding SetStatusCommand}"
CommandParameter="{StaticResource CATLOVER}"
GroupName="SubjectStatusRadioButtonGroup" >
Dog Lover
</RadioButton>
</StackPanel>
</Parent>
How do I bind the View to the ViewModel so that if PetOwnerViewModel.Status returns PetOwnerStatus.CatLover, catLoverRadioButton.IsChecked is true.
There's a fairly well-known bug in WPF with data binding and RadioButtons. This is the way I would normally do it:
The equalityConverter takes a ConverterParameter of an enum and compares it against the binding value (Status). If the values are equal, the converter returns true, which in turn sets IsChecked to true. The IsChecked binding expression above is essentially saying "if the value specified in ConverterParameter equals the value of Status, set IsChecked to true".
Also, you can use the actual enum values by defining the namespace and using x:Static, without having to create separate resources.
Note that you have to give a different GroupName to each RadioButton, otherwise, the WPF bug manifests itself and the bindings get broken.
More details available here: How to bind RadioButtons to an enum?
You can make this sort of thing very dynamic using data-templating, e.g.
(-- Edit: It makes a lot more sense to use a
ListBox
which already has aSelectedItem
property, see this revised answer --)This operates with the raw enum values, you could augment them with display friendly strings using attributes.
Because
IsChecked
is bound on all RadioButtons theRadioButton.GroupName
becomes redundant.(I did not provide my implementation of the
EqualityComparisonConverter
because it's probably crap, it shouldn't be too hard to properly implement it though)