Start with a converter. This is a general purpose converter that will handle any set of values so it will work for any set of radio buttons. I have assumed the field (in my example PayByType) is a string for simplicity, but it doesn't have to be. The Convert method compares the value in the bound field (which is in the value argument) to the value in ConverterParameter (which is in the parameter argument). If they are the same it returns True. If this converter is bound to the IsChecked attribute then the radio button will be checked.
Note that the last radio button for which this converter returns true will be the checked radio button.
The ConvertBack method looks at the value argument. If the converter is bound to the IsChecked attribute then the value will be true or false. If you cause something else to be passed I simply return nothing. If the value is true, then the method returns the ConverterParameter (which is in the parameter argument). If the value is false it returns nothing.
Here is the converter...
Public Class RadioButtonConverter Implements IValueConverter Public Function Convert(value As Object, targetType As System.Type, parameter As Object, culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.Convert Return (value.ToString() = parameter.ToString()) End Function Public Function ConvertBack(value As Object, targetType As System.Type, parameter As Object, culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.ConvertBack If value Is Nothing Or parameter Is Nothing Then Return Nothing End If Dim IsChecked As Boolean = False Boolean.TryParse(value, IsChecked) If IsChecked Then Return parameter Else Return Nothing End If End Function End Class
I will assume you know how to create the static resource, I called mine RadioButtonConverter so the binding looks like this...
<RadioButton Name="EditItemDetailChargeTotalRadio" Content="Charge Total" GroupName="AccountMethod" VerticalAlignment="Center" IsChecked="{Binding Path=PayByType, Mode=TwoWay, Converter={StaticResource RadioButtonConverter}, ConverterParameter='1'}"/> <RadioButton Name="EditItemDetailChargeItemRadio" Content="Charge By Item" GroupName="AccountMethod" VerticalAlignment="Center" IsChecked="{Binding Path=PayByType, Mode=TwoWay, Converter={StaticResource RadioButtonConverter}, ConverterParameter='2'}"/>
Note the only difference in the bindings is the value in ConverterParameter.
No comments:
Post a Comment