In WPF I have a stack panel whose items control defines a data template. This data template is a radio button. The items source is 开发者_开发问答a collection of names on my view model.
So for each name in the view model, a radio button appears on the stack panel with the text beside it for that name (using the content property).
All of these radio buttons have the group set to "name" so selection is mutually exclusive.
My question is, what are my options for binding the content of the selected radio button to a property on my view model "selectedName"?
Ideally I want a UI binding, that is code-free.
Thankyou
I am not sure if you can make use of the mutually exclusiveness there without any event handling. Normally i have this problem with MenuItems or button groups and my approach is to use Multibindings with a EqualityConverter, e.g.
<Setter Property="IsChecked">
<Setter.Value>
<MultiBinding Converter="{StaticResource EqualityComparisonConverter}" Mode="OneWay">
<!-- This binding should find your VM and bind to your property -->
<Binding RelativeSource="{RelativeSource AncestorType=Window}"
Path="DataContext.SelectedName"/>
<!-- Binds to the item being templated -->
<Binding />
</MultiBinding>
</Setter.Value>
</Setter>
A converter (it's not very safe, throws exception if one of the values is null, might want to improve it):
public class EqualityComparisonConverter : IMultiValueConverter
{
#region IMultiValueConverter Members
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
if (values.Length < 2) throw new Exception("At least two inputs are needed for comparison");
bool output = values.Aggregate(true, (acc, x) => acc && x.Equals(values[0]));
return output;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
#endregion
}
Actually it's somewhat of a mystery to me how that even works (considering that the binding is one-way)...
You could create a ViewModel for each RadioButton. It should expose property to bind RadioButton's Checked and some events to notify master ViewModel about it.
精彩评论