Bind a DataGridComboBoxColumn to an Enum - wpf

I have a simple DataGrid which I want the user to add some rows to.
However I want one of the columns to be a ComboBox with it's values taken from an enum.
What's the simplest way of doing this in my XAML?
I've tried following but I get the error "Two-way binding requires Path or XPath"
<Window.Resources>
<ObjectDataProvider x:Key="myEnumData"
MethodName="GetValues"
ObjectType="{x:Type sys:Enum}">
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="local:MyEnum" />
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</Window.Resources>
...
<DataGrid.Columns>
<DataGridComboBoxColumn Header="MyHeader" DisplayMemberPath="EnumValue"
SelectedItemBinding="{Binding Source={StaticResource myEnumData}}">
</DataGridComboBoxColumn>
</DataGrid.Columns>

You are trying to bind the selected item when you (presumably) want to bind the list of available items. Change your binding to this:
<DataGridComboBoxColumn Header="MyHeader"
ItemsSource="{Binding Source={StaticResource myEnumData}, Mode=OneWay}">
</DataGridComboBoxColumn>

XAML
xmlns:ext="clr-namespace:Project.Core.Tools;assembly=Project.Core"
<DataGridComboBoxColumn ItemsSource="{x:Static ext:Extensions.GetEnumTypes}" SelectedItemBinding="{Binding EnumType}" />
Static Class
public static IEnumerable<EnumType> GetEnumTypes => Enum.GetValues(typeof(EnumType)).Cast<EnumType>();

XAML:
<DataGridComboBoxColumn ItemsSource="{Binding Orientantion, Mode=OneTime, Converter={Converts:EnumToItemSourceConverter}}" SelectedItem="{Binding Orientantion}"/>
C#:
public enum OrientantionTypes : int { Custom, Automatic}
public OrientantionType Orientantion { get; set;}
Converter:
public class EnumToItemSourceConverter: MarkupExtension, IValueConverter
{
public override object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (!(value is Enum ))
return null;
{
Type enumType = value.GetType();
var listType = typeof(List<>);
var constructedListType = listType.MakeGenericType(enumType);
var instance = Activator.CreateInstance(constructedListType);
foreach (var m in Enum.GetValues(enumType))
{
((IList)instance).Add(m);
}
return (IList)instance;
}
return null;
}
public virtual object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
return this;
}
}

Related

Bind to a System.Windows Enum from xaml

I am trying to bind a ComboBox ItemsSource to the TextWrapping enum within the System.Windows namespace. The end result would be a drop down where the user can select which type of text wrapping to apply for a given object within my application. Everything works fine when I bind to a custom enum, but I can't figure out what path/source I need to use to bind to an enum within the System.Windows namespace. How can I access this namespace through data binding?
<DataTemplate
DataType="{x:Type MyObjectWrapper}"
>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Text Wrapping" VerticalAlignment="Center" Margin="5,5,0,5"/>
<ComboBox
ItemsSource="{Binding Source={???}, Converter={local:MyEnumConverter}}"
SelectedValuePath="Value"
DisplayMemberPath="Description"
SelectedValue="{Binding Path = TextWrapping}"
VerticalAlignment="Center"
Margin="5"
/>
</StackPanel>
</DataTemplate>
Update: My enum converter just needs the enum class passed in the xaml, which looks like this for custom enums:
<ComboBox
ItemsSource="{Binding Path=MyCreatedEnum, Converter={local:MyEnumConverter}}"
SelectedValuePath="Value"
DisplayMemberPath="Description"
SelectedValue="{Binding Path = TextWrapping}"
VerticalAlignment="Center"
Margin="5"
/>
Found this over the web under this link.
http://brianlagunas.com/a-better-way-to-data-bind-enums-in-wpf/
Here is the modified code to suite your requirement.
<Grid x:Name="LayoutRoot">
<Grid.Resources>
<local:EnumToListConverter x:Key="enumToListConv" />
</Grid.Resources>
<ComboBox
Margin="5"
VerticalAlignment="Center"
ItemsSource="{Binding Source={local:EnumBindingSource {x:Type sysWin1:TextWrapping}}, Converter={StaticResource enumToListConv}}"
SelectedValuePath="Value" />
</Grid>
public class EnumBindingSourceExtension : MarkupExtension
{
private Type _enumType;
public Type EnumType
{
get { return this._enumType; }
set
{
if (value != this._enumType)
{
if (null != value)
{
Type enumType = Nullable.GetUnderlyingType(value) ?? value;
if (!enumType.IsEnum)
throw new ArgumentException("Type must be for an Enum.");
}
this._enumType = value;
}
}
}
public EnumBindingSourceExtension() { }
public EnumBindingSourceExtension(Type enumType)
{
this.EnumType = enumType;
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
if (null == this._enumType)
throw new InvalidOperationException("The EnumType must be specified.");
Type actualEnumType = Nullable.GetUnderlyingType(this._enumType) ?? this._enumType;
return actualEnumType;
}
}
public class EnumToListConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var items = Enum.GetValues((Type)value);
return items;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}

DataGridComboBoxColumn with Enum Converters is not working as expected

I have two converters.One for displaying Enum names and other for converting selected item value to type Enum before passing information to viewmodel.
Everything works fine with combo box.But the same is not working with DataGridComboBoxColumn inside a DataGrid.What am i missing?
class DetectionChemistryDisplaynameListProvider : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var listOfDetectionChemistry = new List<string>();
listOfDetectionChemistry.Add(Enum.GetName(typeof(DetectionChemistryTest), DetectionChemistryTest.Hybridization));
listOfDetectionChemistry.Add(Enum.GetName(typeof(DetectionChemistryTest), DetectionChemistryTest.Hydrolysis));
listOfDetectionChemistry.Add(Enum.GetName(typeof(DetectionChemistryTest), DetectionChemistryTest.Intercalating));
listOfDetectionChemistry.Add(Enum.GetName(typeof(DetectionChemistryTest), DetectionChemistryTest.Others));
return listOfDetectionChemistry;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return value;
}
}
second converter
class DetectionChemistryConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var selectedEnumvalue = (DetectionChemistryTest)value;
var selectedEnumName = Enum.GetName(typeof(DetectionChemistryTest), selectedEnumvalue);
return selectedEnumName;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
var selectedEnumName = (string)value;
var selectedEnumValue = Enum.Parse(typeof(DetectionChemistryTest), selectedEnumName);
return selectedEnumValue;
}
}
Xmal for Resources
<UserControl.Resources>
<converters:DetectionChemistryDisplaynameListProvider x:Key="displayEnumNameConverter" />
<converters:DetectionChemistryConverter x:Key="enumValueConverter"/>
</UserControl.Resources>
Xmal For Combo Box with is working fine
<ComboBox Grid.Row="2" ItemsSource="{Binding Converter={StaticResource displayEnumNameConverter}}" SelectedItem="{Binding SelectedComboDetectionChemistry, Converter={StaticResource enumValueConverter}, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
Xmal for dataGrid which doesn't works
<DataGrid Grid.Row="1" AutoGenerateColumns="False" ItemsSource="{Binding ChannelCombinations}" CanUserAddRows="True">
<DataGrid.Columns>
<DataGridTextColumn Header="Channel" Binding="{Binding ChannelCombinationName}"/>
<DataGridComboBoxColumn Header="DetectionChemistry" ItemsSource="{Binding Converter={StaticResource displayEnumNameConverter}}"
SelectedItemBinding="{Binding SelectedDetectionChemistry, Converter={StaticResource enumValueConverter}, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
/>
</DataGrid.Columns>
</DataGrid>
Say my model looks something like
public class ChannelCombinationTest
{
public string ChannelCombinationName { get; set; }
public DetectionChemistryTest SelectedDetectionChemistry { get; set; }
}
public enum DetectionChemistryTest
{
/// <summary>
///
/// </summary>
Hydrolysis = 0,
/// <summary>
///
/// </summary>
Hybridization = 1,
/// <summary>
///
/// </summary>
Intercalating = 2,
/// <summary>
///
/// </summary>
Others = 3,
}
And my ViewModel is having ObservableCollection of ChannelCombinationTest.
This collection is binded to my datagrid.
I am following MVVM. So i cant afford to use Object Data Provider for my Enum Model.Please suggest accordingly.
The fundamental problem here is that WPF moves in mysterious ways its wonders to perform.
The reason the combo box list does not appear is that WPF needs a governing framework element for the items source. You fix it like this...
<FrameworkElement x:Name="dummyElement" Visibility="Collapsed"/>
<DataGrid Grid.Row="1" AutoGenerateColumns="False" ItemsSource="{Binding ChannelCombinations}" CanUserAddRows="True">
<DataGrid.Columns>
<DataGridTextColumn Header="Channel" Binding="{Binding ChannelCombinationName}"/>
<DataGridComboBoxColumn Header="DetectionChemistry" ItemsSource="{Binding Converter={StaticResource displayEnumNameConverter},Source={x:Reference dummyElement} }"
SelectedValueBinding="{Binding SelectedDetectionChemistry, Converter={StaticResource enumValueConverter}}"
/>
<DataGridTextColumn Header="DetectionChemistry" Binding="{Binding SelectedDetectionChemistry, Converter={StaticResource enumValueConverter}}"/>
</DataGrid.Columns>
</DataGrid>

binding radiobuttons group to a property in WPF

Let's imagine that I have:
<RadioButton GroupName="Group1" IsChecked="{Binding Path=RadioButton1IsChecked}" />
<RadioButton GroupName="Group1" IsChecked="{Binding Path=RadioButton2IsChecked}" />
And then in my data source class I have:
public bool RadioButton1IsChecked { get; set; }
public bool RadioButton2IsChecked { get; set; }
public enum RadioButtons { RadioButton1, RadioButton2, None }
public RadioButtons SelectedRadioButton
{
get
{
if (this.RadioButtonIsChecked)
return RadioButtons.RadioButton1;
else if (this.RadioButtonIsChecked)
return RadioButtons.RadioButton2;
else
return RadioButtons.None;
}
}
Can I somehow bind my radio buttons directly to SelectedRadioButton property? I really need RadioButton1IsChecked and RadioButton2IsChecked properties only to calculate the selected radiobutton.
Declare an enumeration similar to:
enum RadioOptions {Option1, Option2}
XAML:
<RadioButton IsChecked="{Binding SelectedOption, Converter={StaticResource EnumBooleanConverter}, ConverterParameter={x:Static local:RadioOptions.Option1}}"/>
<RadioButton IsChecked="{Binding SelectedOption, Converter={StaticResource EnumBooleanConverter}, ConverterParameter={x:Static local:RadioOptions.Option2}}"/>
Converter class:
public class EnumBooleanConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value.Equals(parameter);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return ((bool)value) ? parameter : Binding.DoNothing;
}
}
<RadioButton GroupName="Group1" IsChecked="{Binding Path=SelectedRadioButton, Converter={StaticResource EnumBooleanConverter}, ConverterParameter=RadioButton1}" />
<RadioButton GroupName="Group1" IsChecked="{Binding Path=SelectedRadioButton, Converter={StaticResource EnumBooleanConverter}, ConverterParameter=RadioButton2}" />
public enum RadioButtons { RadioButton1, RadioButton2, None }
public RadioButtons SelectedRadioButton {get;set;}
public class EnumBooleanConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var ParameterString = parameter as string;
if (ParameterString == null)
return DependencyProperty.UnsetValue;
if (Enum.IsDefined(value.GetType(), value) == false)
return DependencyProperty.UnsetValue;
object paramvalue = Enum.Parse(value.GetType(), ParameterString);
return paramvalue.Equals(value);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
var ParameterString = parameter as string;
var valueAsBool = (bool) value;
if (ParameterString == null || !valueAsBool)
{
try
{
return Enum.Parse(targetType, "0");
}
catch (Exception)
{
return DependencyProperty.UnsetValue;
}
}
return Enum.Parse(targetType, ParameterString);
}
}
We can create the radio buttons dynamically, ListBox can help us do that, without converters, quite simple.
The advantage is below:
if someday your enum class changes, you do not need to update the GUI (XAML file).
The steps are below:
create a ListBox and set the ItemsSource for the listbox as the enum and binding the SelectedItem of the ListBox to the Selected property.
Then the Radio Buttons for each ListBoxItem will be created.
public enum RadioButtons
{
RadioButton1,
RadioButton2,
None
}
Step 1: add the enum to static resources for your Window, UserControl or Grid etc.
<Window.Resources>
<ObjectDataProvider MethodName="GetValues"
ObjectType="{x:Type system:Enum}"
x:Key="RadioButtons">
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="local:RadioButtons" />
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</Window.Resources>
Step 2: Use the List Box and Control Template to populate each item inside as Radio button
<ListBox ItemsSource="{Binding Source={StaticResource RadioButtons}}" SelectedItem="{Binding SelectedRadioButton, Mode=TwoWay}" >
<ListBox.Resources>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<RadioButton
Content="{TemplateBinding ContentPresenter.Content}"
IsChecked="{Binding Path=IsSelected,
RelativeSource={RelativeSource TemplatedParent},
Mode=TwoWay}" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.Resources>
</ListBox>
Now, enjoy~
References:
https://brianlagunas.com/a-better-way-to-data-bind-enums-in-wpf/
XAML:
<RadioButton IsChecked="{Binding Path=SelectedOption, UpdateSourceTrigger=PropertyChanged}">Option1</RadioButton>
<RadioButton IsChecked="{Binding Path=SelectedOption, UpdateSourceTrigger=PropertyChanged, Converter={v:NotBoolenConverter}}">Option2</RadioButton>
Converter:
public class NotBoolenConverter : IValueConverter
{
public NotBoolenConverter()
{
}
public override object Convert(
object value,
Type targetType,
object parameter,
CultureInfo culture)
{
bool output = (bool)value;
return !output;
}
public override object ConvertBack(
object value,
Type targetType,
object parameter,
CultureInfo culture)
{
bool output = (bool)value;
return !output;
}
}
Works with 2 radio buttons, by binding one to the opposite of the other.

ComboBox - bind selected value

I want to bind the combobox's selected value to the bounded object property, and also set the selected index of every combobox to 0.
The problem is that only first combo shows the selected item.
public enum SubEnum1
{
Apple=1,
Banana=2,
Pear=3
}
public enum FullEnum
{
Apple=1,
Banana=2,
Pear=3,
Cucumber=4,
Tomato=5,
Onion=6
}
Im XAML window i have some data control (list) where is a datatemplate that has a combobox.
comboboxes are bounded to SubEnum1.
The data-control is bounded to an object-collection:
List<MyObject> collection = new List<MyObject>()
//collection.Add...
mylist.ItemsSource = collection;
public class MyObject
{
public FullEnum TheSelectedEnum {get;set;}
....
//other properties
}
public class EnumConverter2 : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value != null)
return (FullEnum)value;
else return "";
}
}
<ObjectDataProvider x:Key="Enum1"
MethodName="GetValues"
ObjectType="{x:Type sys:Enum}">
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="local:SubEnum1" />
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
<ListBox Height="261" HorizontalAlignment="Left" Name="mylist" VerticalAlignment="Top" Width="278">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<ComboBox Height="23" Width="90"
ItemsSource="{Binding Source={StaticResource Enum1}}"
SelectedValue="{Binding Path=TheSelectedEnum, Converter={StaticResource enumConverter}}"
SelectedIndex="0"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
(If I expand other comboboxes I see the values)
Update to post:
Maybe I can somehow else pass the selected value to the binded object?
You can do this and solve your problem:
public enum SubEnum1
{
None=0,
Apple=1,
Banana=2,
Pear=3
}
Then use FallbackValue:
<ComboBox Height="23" Width="90"
ItemsSource="{Binding Source={StaticResource Enum1}}"
SelectedValue="{Binding Path=TheSelectedEnum, FallbackValue=0}" />

WPF MVVM Radio buttons on ItemsControl

I've bound enums to radio buttons before, and I generally understand how it works. I used the alternate implementation from this question: How to bind RadioButtons to an enum?
Instead of enumerations, I'd like to generate a runtime-enumerated set of a custom type and present those as a set of radio buttons. I have gotten a view working against a runtime-enumerated set with a ListView, binding to the ItemsSource and SelectedItem properties, so my ViewModel is hooked up correctly. Now I am trying to switch from a ListView to a ItemsControl with radio buttons.
Here's as far as I've gotten:
<Window.Resources>
<vm:InstanceToBooleanConverter x:Key="InstanceToBooleanConverter" />
</Window.Resources>
<!-- ... -->
<ItemsControl ItemsSource="{Binding ItemSelections}">
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type vm:ISomeType}">
<RadioButton Content="{Binding Name}"
IsChecked="{Binding Path=SelectedItem, Converter={StaticResource InstanceToBooleanConverter}, ConverterParameter={Binding}}"
Grid.Column="0" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
InstanceToBooleanConverter has the same implementation as EnumToBooleanConverter from that other question. This seems right, since it seems like it just invokes the Equals method:
public class InstanceToBooleanConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return value.Equals(parameter);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return value.Equals(true) ? parameter : Binding.DoNothing;
}
}
The problem I am getting now is that I can't figure out how to send a runtime value as the ConverterParameter. When I try (with the code above), I get this error:
A 'Binding' cannot be set on the 'ConverterParameter' property of type 'Binding'. A 'Binding' can only be set on a DependencyProperty of a DependencyObject.
Is there a way to bind to the item instance, and pass it to the IValueConverter?
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.
MultiBinding Class
IMultiValueConverter Interface
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; }
}
}
Now that I know about x:Shared (thanks to your other question), I renounce my previous answer and say that a MultiBinding is the way to go after all.
The XAML:
<StackPanel>
<TextBlock Text="{Binding SelectedChoice}" />
<ItemsControl ItemsSource="{Binding Choices}">
<ItemsControl.Resources>
<local:MyConverter x:Key="myConverter" x:Shared="false" />
</ItemsControl.Resources>
<ItemsControl.ItemTemplate>
<DataTemplate>
<RadioButton>
<RadioButton.IsChecked>
<MultiBinding Converter="{StaticResource myConverter}" >
<Binding Path="DataContext.SelectedChoice" RelativeSource="{RelativeSource AncestorType=UserControl}" />
<Binding Path="DataContext" RelativeSource="{RelativeSource Mode=Self}" />
</MultiBinding>
</RadioButton.IsChecked>
<TextBlock Text="{Binding}" />
</RadioButton>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
The viewmodel:
class Viewmodel : INPC
{
public Viewmodel()
{
Choices = new List<string>() { "one", "two", "three" };
SelectedChoice = Choices[0];
}
public List<string> Choices { get; set; }
string selectedChoice;
public string SelectedChoice
{
get { return selectedChoice; }
set
{
if (selectedChoice != value)
{
selectedChoice = value;
OnPropertyChanged("SelectedChoice");
}
}
}
}
The converter:
public class MyConverter : IMultiValueConverter
{
object selectedValue;
object myValue;
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
selectedValue = values[0];
myValue = values[1];
return selectedValue == myValue;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
if ((bool)value)
{
return new object[] { myValue, Binding.DoNothing };
}
else
{
return new object[] { Binding.DoNothing, Binding.DoNothing };
}
}
}

Resources