将 RadioButton 绑定到枚举

Binding RadioButton to Enum

问题: 使用参数化转换器将枚举类型的 属性 绑定到 RadioButtons。没有抛出异常,Radiobutton 可能有验证问题(不确定)。测试时显示 RadioButtons 周围的红色框。

信息: 试图使用中给出的解决方案 How to bind RadioButtons to an enum?

我有一个这样的枚举:

namespace crmVerwaltungstools.Models
{
   public enum CrmSystemType
   {
     Training = 0,
     Live = 1
   }
}

BooleanToEnumConverter:

    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) ? (CrmSystemType)parameter : Binding.DoNothing;
    }

在我的 Window 里面:

xmlns:models="clr-namespace:crmVerwaltungstool.Models"

     <StackPanel Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="1" Orientation="Horizontal">
          <StackPanel.Resources>
                <converter:RadioButtonIsCheckedToCrmSystemTypeConverter x:Key="RbIsCheckedToCrmSystemTypeConverter" />
          </StackPanel.Resources>

          <RadioButton Content="Schulungs-System" GroupName="rbg_SelectSystem"
                                 IsChecked="{Binding Path=SystemType, Converter={StaticResource RbIsCheckedToCrmSystemTypeConverter},
                                 ConverterParameter={x:Static models:CrmSystemType.Training}}"/>
          <RadioButton Content="Live-System" GroupName="rbg_SelectSystem"
                                 IsChecked="{Binding Path=SystemType, Converter={StaticResource RbIsCheckedToCrmSystemTypeConverter},
                                 ConverterParameter={x:Static models:CrmSystemType.Live}}"/>
      </StackPanel>

看不出任何错误。 (可能是今天代码看多了...)

感谢帮助!!

首先您需要检查您的转换器,该值不为空:

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value == null)
        {
            return false;
        }
        return value.Equals(parameter);
    }

也在 ConvertBack 方法中执行此操作。

其次,写下你的xaml类似的东西:

<StackPanel>
    <StackPanel.Resources>          
        <local:EnumToBooleanConverter x:Key="EnumToBooleanConverter" />          
    </StackPanel.Resources>
    <RadioButton IsChecked="{Binding Path=YourEnumProperty, Converter={StaticResource EnumToBooleanConverter}, ConverterParameter={x:Static local:YourEnumType.Enum1}}" />
    <RadioButton IsChecked="{Binding Path=YourEnumProperty, Converter={StaticResource EnumToBooleanConverter}, ConverterParameter={x:Static local:YourEnumType.Enum2}}" />
</StackPanel>

问题已解决。

我在我的视图模型中发现了一小段旧代码,我在其中尝试将我的枚举定义为内部 class。

所以,基本上,我的程序对使用哪个枚举感到困惑 - viewmodel 中的内部 class 或 models 文件夹中的外部 class。

删除内部枚举后,一切正常。