I have a radio button group in a listview. The rows of this listview (which contain the radio button grp amongst other things) is an observable collection.
the code I have written goes something like this:
The Xaml:
<RadioButton Content="EnumValueName1"
GroupName="RadButGrp1"
IsChecked="{Binding propertyName,Mode=TwoWay,Converter={StaticResource EnumToBoolConverter},ConverterParameter=EnumValueName1}" >
</RadioButton>
<RadioButton Content="EnumValueName2"
GroupName="RadButGrp1"
IsChecked="{Binding propertyName,Mode=TwoWay,Converter={StaticResource EnumToBoolConverter},ConverterParameter=EnumValueName2}">
</RadioButton>
<RadioButton Content="EnumValueName3"
GroupName="RadButGrp1"
IsChecked="{Binding propertyName,Mode=TwoWay,Converter={StaticResource EnumToBoolConverter},ConverterParameter=EnumValueName3}">
</RadioButton>
I am trying to bind directly to the data field called propertyName in my data structure defining the table that holds these values. I do NOT have this field in my ViewModel class for this view. I did this to avoid keeping track of the index of the collection that I am currently populating. (or so i'd like to think!)
The converter:
public class EnumBooleanConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string parameterString = parameter as string;
if (parameterString == null)
return DependencyProperty.UnsetValue;
if (value == null || Enum.IsDefined(value.GetType(), value) == false)
return DependencyProperty.UnsetValue;
object parameterValue = Enum.Parse(value.GetType(), parameterString);
return parameterValue.Equals(value);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string parameterString = parameter as string;
if (parameterString == null || value.Equals(false))
return DependencyProperty.UnsetValue;
return Enum.Parse(targetType, parameterString);
}
}
The problem is that in the ConvertBack function at the Enum.Parse line, the following Argument exception occurs:
Type provided must be an Enum. Parameter name: enumType
Is there a way to return an enum type to the binding? How do I tell the radio buttons which enumeration value it represents? How do I write a function that returns the appropriate enum value to the binding?
Hoping you guys can help. Thanks in advance!
Try this, it's my version of the
EnumToBoolConverter
:Ok the solution was relatively simple once I got the concept right. I have done the following which partially solves my problem.
The targetType in my ConvertBack function now the correct enum type. Hope this helps!
Now i have to figure out how to make the radiobuttons retain selections in multiple rows of the listview. Presently they a selection in first row deselects the same group from the rest of the rows.
Thank you for your help so far. If anyone can point me to a solution for the new problem that would be really great!