如图样:
在View中:
<RadioButton IsChecked="{Binding Option, Converter={cvt:EnumToBooleanConverter},ConverterParameter={x:Static enum:RadionButtonOptions.One}}" Content="One" DockPanel.Dock="Top"/> <RadioButton IsChecked="{Binding Option, Converter={cvt:EnumToBooleanConverter},ConverterParameter={x:Static enum:RadionButtonOptions.Two}}" Content="Two" DockPanel.Dock="Top"/> <RadioButton IsChecked="{Binding Option, Converter={cvt:EnumToBooleanConverter},ConverterParameter={x:Static enum:RadionButtonOptions.Three}}" Content="Two" DockPanel.Dock="Top"/>
在ViewModel中:
public const string OptionPropertyName = "Option"; private RadionButtonOptions _option; public RadionButtonOptions Option { get { return _option; } set { if (_option == value) return; _option = value; RaisePropertyChanged(OptionPropertyName); } }
Converter:
[MarkupExtensionReturnType(typeof(EnumToBooleanConverter))] [ValueConversion(typeof(Enum), typeof(bool))] public class EnumToBooleanConverter : MarkupExtension, IValueConverter { private static EnumToBooleanConverter converter = null; public override object ProvideValue(IServiceProvider serviceProvider) { if (null == converter) { converter = new EnumToBooleanConverter(); } return converter; } 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; } }
枚举类型:
public enum RadionButtonOptions { One, Two, Three, }
================================================================================
整理代码之后把转换器的ConvertBack方法体错写成
return Binding.DoNothing;
也是醉了。
。
时间: 2024-10-06 21:18:40