I had a property in my View Model, of an Enum type, and wanted to bind multiple radio buttons to this.
Firstly, I wrote a simple Enum to Bool converter, like this.
And my enumeration is like
Firstly, I wrote a simple Enum to Bool converter, like this.
public class EnumToBoolConverter : IValueConverter { #region IValueConverter Members public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (parameter.Equals(value)) return true; else return false; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return parameter; } #endregion }
And my enumeration is like
public enum CompanyTypes { Type1Comp, Type2Comp, Type3Comp }Now, in my XAML, I provided the enumeration as the ConverterParameter, of the Converter we wrote earlier, like
<Window x:Class="WpfTestRadioButtons.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WpfTestRadioButtons" Title="Window1" Height="300" Width="300"> <Window.Resources> <local:EnumToBoolConverter x:Key="EBConverter"/> </Window.Resources> <Grid> <StackPanel> <RadioButton IsChecked="{Binding Path=Type, Converter={StaticResource EBConverter}, ConverterParameter={x:Static local:CompanyTypes.Type1Comp}}" Content="Type1"/> <RadioButton IsChecked="{Binding Path=Type, Converter={StaticResource EBConverter}, ConverterParameter={x:Static local:CompanyTypes.Type2Comp}}" Content="Type2"/> </StackPanel> </Grid> </Window>Now, in the view model, I exposed a property named Type, which is of the CompanyEnum type. Like,
public CompanyTypes Type { get { return _type; } set { _type = value; if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("Type")); } }And it seems that I'm pretty much done. Alternatively, you can use the same idea to pass an integer, but in that case, you need to change the converter a bit. See the NumToBool converter I mentioned earlier :)
Thanks this was very helpful
ReplyDelete