数据绑定WPF中的Enum属性

Kil*_*ine 10 c# data-binding wpf xaml

以下是我所拥有的课程的简化示例:

public class ExampleClassDto 
{
     public int DriverTypeId
}
Run Code Online (Sandbox Code Playgroud)

我还有一个Enum,它将DriverType的Ids映射到有意义的名称:

public enum DriverType
{
    None,
    Driver1,
    Driver2,
    Driver3
}
Run Code Online (Sandbox Code Playgroud)

但是我希望将它在XAML中绑定到一个组合框.不幸的是,由于类型不匹配,它不喜欢这个.所以在我的ViewModel中,我必须创建第二个属性来映射这两个

public class ExampleViewModel
{
    private ExampleClassDto _selectedExampleClass;
    public ExampleClassDto SelectedExampleClass
    {
        get { return _selectedExampleClass; }
        set
        {
            _selectedExampleClass = value;
            SelectedDriverType = (DriverType)_selectedExampleClass.DriverTypeId;
            OnPropertyChanged("SelectedDeviceType");
        }
    }

public DriverType SelectedDriverType
{
    get
        {
            if (_selectedDeviceType != null) 
            { 
                return (DriverType)_selectedDeviceType.DriverTypeId;
            }
            return DriverType.None;
        }
        set
        {
            _selectedDeviceType.DriverTypeId = (int) value;
            OnPropertyChanged("SelectedDriverType");
        }
}
}
Run Code Online (Sandbox Code Playgroud)

然后我绑定到新属性.

<ComboBox ItemsSource="{Binding Source={StaticResource DriverTypeEnum}}" SelectedValue="{Binding SelectedDriverType, Mode=TwoWay}"/>
Run Code Online (Sandbox Code Playgroud)

现在,这个工作,但感觉非常严重.它使用SelectedDriverType作为转换器.我想避免让DTO的属性成为另一种类型.还有其他更优雅的解决方案吗?

谢谢!

Roh*_*ats 23

您可以使用通用转换器说明EnumConverterconvert int to Enum在XAML上显示它并convert back from Enum to int在ViewModel类中重新设置.

它适用于任何枚举类型.你只需要在转换器参数中传递枚举类型.

public class EnumConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, 
                          System.Globalization.CultureInfo culture)
    {
        Enum enumValue = default(Enum);
        if (parameter is Type)
        {
            enumValue = (Enum)Enum.Parse((Type)parameter, value.ToString());
        }
        return enumValue;
     }

     public object ConvertBack(object value, Type targetType, object parameter, 
                               System.Globalization.CultureInfo culture)
     {
         int returnValue = 0;
         if (parameter is Type)
         {
             returnValue = (int)Enum.Parse((Type)parameter, value.ToString());
         }
         return returnValue;
     }
}
Run Code Online (Sandbox Code Playgroud)

XAML用法:

<ComboBox ItemsSource="{Binding Source={StaticResource DriverTypeEnum}}"
          SelectedValue="{Binding DriverTypeId,
                                Converter={StaticResource EnumConverter}, 
                                ConverterParameter={x:Type local:DriverType}}"/>
Run Code Online (Sandbox Code Playgroud)

local 是声明DriverType的名称空间.

  • 真棒.这很有效.只需要将以下内容添加到我的主资源字典中就可以使用EnumConverter作为资源:`<converter:EnumConverter xmlns:converter ="clr-namespace:Some.Name.Space.Helpers"x:Key ="EnumConverter"/ >`.SUPER很高兴我可以在我使用Enums的其他ViewModel中重用它.谢谢! (2认同)

Dre*_*kes 7

接受的答案要求您在每个绑定上将枚举类型指定为转换器参数.

如果绑定到枚举属性,则转换器可以从targetType属性中确定枚举类型,这可以更符合人体工程学且不易出错.

public sealed class BidirectionalEnumAndNumberConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null)
            return null;

        if (targetType.IsEnum)
        {
            // convert int to enum
            return Enum.ToObject(targetType, value);
        }

        if (value.GetType().IsEnum)
        {
            // convert enum to int
            return System.Convert.ChangeType(
                value,
                Enum.GetUnderlyingType(value.GetType()));
        }

        return null;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        // perform the same conversion in both directions
        return Convert(value, targetType, parameter, culture);
    }
}
Run Code Online (Sandbox Code Playgroud)

这也适用不管底层枚举类型(的int,short,byte...).

调用时,此转换器将纯粹基于valuetargetType值在int/enum值之间翻转值的类型.源代码中没有硬编码的枚举类型,因此它非常可重用.