WPF中多个RadioButton绑定到一个属性

如图样:

WPF中多个RadioButton绑定到一个属性

在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;

也是醉了。

上一篇:【Zabbix】 Zabbix表结构说明【转载】


下一篇:java如何在eclipse编译时自动生成代码