用Enumeration值绑定组合框,并以enum

时间:2018-10-26 08:07:47

标签: c# .net wpf

我有一个枚举:

public enum InspectionCardsGroupOption
   {
      Application = 0,
      ApplicationType,
      InspectionStation,
      ComponentSide
   };

现在我正在使用wpf MVVM设计模式。该枚举在ViewModel中。 我在xaml中有一个ComboBox。 我需要将该ComboBox绑定到此枚举,并且在选择ComboBox时,应以枚举值的形式给我枚举值。

平台:Windows10,语言:C# 我是编程新手,所以如果有人可以给我详尽的解释,那对我会有所帮助。

2 个答案:

答案 0 :(得分:0)

首先在xaml中的Resource标签内创建一个ObjectDataProvider:

<ObjectDataProvider  x:Key="odpEnum"
                         MethodName="GetValues" ObjectType="{x:Type sys:Enum}">
        <ObjectDataProvider.MethodParameters>
            <x:Type TypeName="local:Comparators"/>
        </ObjectDataProvider.MethodParameters>
    </ObjectDataProvider>
    <local:EnumDescriptionConverter x:Key="enumDescriptionConverter"></local:EnumDescriptionConverter>

现在在上面的代码示例中,sys:Enum具有别名sys,该别名sys来自命名空间xmlns:sys =“ clr-namespace:System; assembly = mscorlib”。因此,需要添加它。

添加如下所示的组合框:

<ComboBox Grid.Row="1" Grid.Column="1"  Height="25" Width="100" Margin="5" 
          ItemsSource="{Binding Source={StaticResource odpEnum}}"
          SelectedItem="{Binding Path=MySelectedItem}"
          >
            <ComboBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Converter={StaticResource enumDescriptionConverter}}"/>
                </DataTemplate>
            </ComboBox.ItemTemplate>
        </ComboBox>

让我认为您的枚举类型如下:

public enum Comparators
{
    [Description("Application")]
    Application,
    [Description("Application Type")]
    ApplicationType,
    [Description("Inspection Name")]
    InspectionName,
    [Description("Component Type")]
    ComponentType
}

因此请将其保存在viewmodel部分中(在视图模型之外,但与viewmodel相同的名称空间内)

现在如下在viewmodel中创建一个属性,以从XAML ComboBox中获取selectedItem

private Comparators _MySelectedItem;
    public Comparators MySelectedItem
    {
        get { return _MySelectedItem; }
        set
        {
            _MySelectedItem = value;
            OnPropertyChanged("MySelectedItem");
        }
    }

创建如下的转换器类:-

public class EnumDescriptionConverter : IValueConverter
{
    private string GetEnumDescription(Enum enumObj)
    {
        FieldInfo fieldInfo = enumObj.GetType().GetField(enumObj.ToString());

        object[] attribArray = fieldInfo.GetCustomAttributes(false);

        if (attribArray.Length == 0)
        {
            return enumObj.ToString();
        }
        else
        {
            DescriptionAttribute attrib = attribArray[0] as DescriptionAttribute;
            return attrib.Description;
        }
    }

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {            
        Enum myEnum = (Comparators)value;            
        string description = GetEnumDescription(myEnum);
        return description;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return string.Empty;
    }
}

当您运行此示例时,您会发现您将获得_MySelectedItem = value枚举类型的selectedItem;在视图模型的属性中。

答案 1 :(得分:0)

这可以通过MVVM的纯方式并带有几个帮助程序类来实现。

myValueDisplayPair.cs

/// <summary>
/// Equivalent to KeyValuePair<object, string> but with more memorable property names for use with ComboBox controls
/// </summary>
/// <remarks>
/// Bind ItemsSource to IEnumerable<ValueDisplayPair>, set DisplayMemberPath = Display, SelectedValuePath = Value, bind to SelectedValue
/// </remarks>
public abstract class myValueDisplayPair
{
    public object Value { get; protected set; }
    public string Display { get; protected set; }
}

/// <summary>
/// Equivalent to KeyValuePair<T, string>
/// </summary>
/// <typeparam name="T"></typeparam>
public class myValueDisplayPair<T> : myValueDisplayPair
{
    internal perValueDisplayPair(T value, string display)
    {
        Value = value;
        Display = display;
    }

    public new T Value { get; }

    public override string ToString() => $"Display: {Display} Value: {Value}";
}

myEnumHelper.cs

/// <summary>
/// Helper class for enum types 
/// </summary>
public static class myEnumExtender
{
    /// <summary>
    /// Get the value of a Description attribute assigned to an enum element 
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static string Description(this Enum value)
    {
        var fieldInfo = value
            .GetType()
            .GetField(value.ToString());

        var attributes = fieldInfo
            .GetCustomAttributes(typeof(DescriptionAttribute), false)
            .OfType<DescriptionAttribute>()
            .ToList();

        return attributes.Any() ? attributes.First().Description : value.ToString();
    }

    /// <summary>
    /// Gets all the elements of an enum type 
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <remarks>
    /// c# doesn't support where T: Enum - this is the best compromise
    /// </remarks>
    public static ReadOnlyCollection<T> GetValues<T>() 
        where T : struct, IComparable, IFormattable, IConvertible
    {
        var itemType = typeof (T);

        if (!itemType.IsEnum)
            throw new ArgumentException($"Type '{itemType.Name}' is not an enum");

        var fields = itemType
            .GetFields()
            .Where(field => field.IsLiteral);

        return fields
            .Select(field => field.GetValue(itemType))
            .Cast<T>()
            .ToList()
            .AsReadOnly();
    }

    /// <summary>
    /// Generate a <see cref="myValueDisplayPair"/> list containing all elements of an enum type
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="sortByDisplay"></param>
    public static ReadOnlyCollection<myValueDisplayPair<T>> MakeValueDisplayPairs<T>(bool sortByDisplay = false) 
        where T : struct, IComparable, IFormattable, IConvertible
    {
        var itemType = typeof(T);

        if (!itemType.IsEnum)
            throw new ArgumentException($"Type '{itemType.Name}' is not an enum");

        var values = GetValues<T>();
        var result = values
            .Select(v => v.CreateValueDisplayPair())
            .ToList();

        if (sortByDisplay)
            result.Sort((p1, p2) => string.Compare(p1.Display, p2.Display, StringComparison.InvariantCultureIgnoreCase));

        return result.AsReadOnly();
    }
}

这些可以在您的ViewModel中使用

public ReadOnlyCollection<lcValueDisplayPair<InspectionCardsGroupOption>> AllInspectionCardsGroupOptions { get; } 
    = myEnumExtender.MakeValueDisplayPairs<InspectionCardsGroupOption>();

private InspectionCardsGroupOption _selectedInspectionCardsGroupOption;

public InspectionCardsGroupOption SelectedInspectionCardsGroupOption
{
    get => _selectedInspectionCardsGroupOption;
    set => Set(nameof(SelectedInspectionCardsGroupOption), ref _selectedInspectionCardsGroupOption, value)
}

并在您的视图中

<ComboBox ItemsSource="{Binding AllInspectionCardsGroupOptions}"
          DisplayMemberPath="Display"
          SelectedValuePath="Value"
          SelectedValue="{Binding SelectedAllInspectionCardsGroupOptions, mode=TwoWay}"