WPF MVVM Radio buttons on ItemsControl WPF MVVM Radio buttons on ItemsControl wpf wpf

WPF MVVM Radio buttons on ItemsControl


It turns out that it is much simpler to abandon using ItemsControl and instead go with ListBox.

It may be more heavy-weight, but that's mostly because it is doing the heavy lifting for you. It is really easy to do a two-way binding between RadioButton.IsChecked and ListBoxItem.IsSelected. With the proper control template for the ListBoxItem, you can easily get rid of all the selection visual.

<ListBox ItemsSource="{Binding Properties}" SelectedItem="{Binding SelectedItem}">    <ListBox.ItemContainerStyle>        <!-- Style to get rid of the selection visual -->        <Style TargetType="{x:Type ListBoxItem}">            <Setter Property="Template">                <Setter.Value>                    <ControlTemplate TargetType="{x:Type ListBoxItem}">                        <ContentPresenter />                    </ControlTemplate>                </Setter.Value>            </Setter>        </Style>    </ListBox.ItemContainerStyle>    <ListBox.ItemTemplate>        <DataTemplate DataType="{x:Type local:SomeClass}">            <RadioButton Content="{Binding Name}" GroupName="Properties">                <!-- Binding IsChecked to IsSelected requires no support code -->                <RadioButton.IsChecked>                    <Binding Path="IsSelected"                             RelativeSource="{RelativeSource AncestorType=ListBoxItem}"                             Mode="TwoWay" />                </RadioButton.IsChecked>            </RadioButton>        </DataTemplate>    </ListBox.ItemTemplate></ListBox>


As far as I know, there's no good way to do this with a MultiBinding, although you initially think there would be. Since you can't bind the ConverterParameter, your ConvertBack implementation doesn't have the information it needs.

What I have done is created a separate EnumModel class solely for the purpose of binding an enum to radio buttons. Use a converter on the ItemsSource property and then you're binding to an EnumModel. The EnumModel is just a forwarder object to make binding possible. It holds one possible value of the enum and a reference to the viewmodel so it can translate a property on the viewmodel to and from a boolean.

Here's an untested but generic version:

<ItemsControl ItemsSource="{Binding Converter={StaticResource theConverter} ConverterParameter="SomeEnumProperty"}">    <ItemsControl.ItemTemplate>        <DataTemplate>            <RadioButton IsChecked="{Binding IsChecked}">                <TextBlock Text="{Binding Name}" />            </RadioButton>        </DataTemplate>    </ItemsControl.ItemTemplate></ItemsControl>

The converter:

public class ToEnumModelsConverter : IValueConverter{    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)    {        var viewmodel = value;        var prop = viewmodel.GetType().GetProperty(parameter as string);        List<EnumModel> enumModels = new List<EnumModel>();        foreach(var enumValue in Enum.GetValues(prop.PropertyType))        {            var enumModel = new EnumModel(enumValue, viewmodel, prop);            enumModels.Add(enumModel);        }        return enumModels;    }    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)    {        throw new NotImplementedException();    }}

The EnumModel:

public class EnumModel : INPC{    object enumValue;    INotifyPropertyChanged viewmodel;    PropertyInfo property;    public EnumModel(object enumValue, object viewmodel, PropertyInfo property)    {        this.enumValue = enumValue;        this.viewmodel = viewmodel as INotifyPropertyChanged;        this.property = property;        this.viewmodel.PropertyChanged += new PropertyChangedEventHandler(viewmodel_PropertyChanged);    }    void viewmodel_PropertyChanged(object sender, PropertyChangedEventArgs e)    {        if (e.PropertyName == property.Name)        {            OnPropertyChanged("IsChecked");        }    }    public bool IsChecked    {        get        {            return property.GetValue(viewmodel, null).Equals(enumValue);        }        set        {            if (value)            {                property.SetValue(viewmodel, enumValue, null);            }        }    }}

For a code sample that I know works (but it's still quite unpolished - WIP!), you can see http://code.google.com/p/pdx/source/browse/trunk/PDX/PDX/Toolkit/EnumControl.xaml.cs. This only works within the context of my library, but it demonstrates setting the Name of the EnumModel based on the DescriptionAttribute, which might be useful to you.


You are so close. When you are need two bindings for one converter you need a MultiBinding and a IMultiValueConverter! The syntax is a little more verbose but no more difficult.

Edit:

Here's a little code to get you started.

The binding:

<RadioButton Content="{Binding Name}"        Grid.Column="0">    <RadioButton.IsChecked>        <MultiBinding Converter="{StaticResource EqualsConverter}">            <Binding Path="SelectedItem"/>            <Binding Path="Name"/>        </MultiBinding>    </RadioButton.IsChecked></RadioButton>

and the converter:

public class EqualsConverter : IMultiValueConverter{    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)    {        return values[0].Equals(values[1]);    }    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)    {        throw new NotImplementedException();    }}

Second Edit:

The above approach is not useful to implement two-way binding using the technique linked in the question because the necessary information is not available when converting back.

The correct solution I believe is straight-up MVVM: code the view-model to match the needs of the view. The amount of code is quite small and obviates the need for any converters or funny bindings or tricks.

Here is the XAML;

<Grid>    <ItemsControl ItemsSource="{Binding}">        <ItemsControl.ItemTemplate>            <DataTemplate>                <RadioButton                    GroupName="Value"                    Content="{Binding Description}"                    IsChecked="{Binding IsChecked, Mode=TwoWay}"/>            </DataTemplate>        </ItemsControl.ItemTemplate>    </ItemsControl></Grid>

and code-behind to simulate the view-model:

        DataContext = new CheckBoxValueCollection(new[] { "Foo", "Bar", "Baz" });

and some view-model infrastructure:

    public class CheckBoxValue : INotifyPropertyChanged    {        private string description;        private bool isChecked;        public string Description        {            get { return description; }            set { description = value; OnPropertyChanged("Description"); }        }        public bool IsChecked        {            get { return isChecked; }            set { isChecked = value; OnPropertyChanged("IsChecked"); }        }        public event PropertyChangedEventHandler PropertyChanged;        protected void OnPropertyChanged(string propertyName)        {            if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName));        }    }    public class CheckBoxValueCollection : ObservableCollection<CheckBoxValue>    {        public CheckBoxValueCollection(IEnumerable<string> values)        {            foreach (var value in values)                this.Add(new CheckBoxValue { Description = value });            this[0].IsChecked = true;        }        public string SelectedItem        {            get { return this.First(item => item.IsChecked).Description; }        }    }