Databinding an enum property to a ComboBox in WPF

后端 未结 13 1506
北海茫月
北海茫月 2020-11-22 15:46

As an example take the following code:

public enum ExampleEnum { FooBar, BarFoo }

public class ExampleClass : INotifyPropertyChanged
{
    private ExampleEn         


        
13条回答
  •  不知归路
    2020-11-22 16:33

    My favorite way to do this is with a ValueConverter so that the ItemsSource and SelectedValue both bind to the same property. This requires no additional properties to keep your ViewModel nice and clean.

    
    

    And the definition of the Converter:

    public static class EnumHelper
    {
      public static string Description(this Enum e)
      {
        return (e.GetType()
                 .GetField(e.ToString())
                 .GetCustomAttributes(typeof(DescriptionAttribute), false)
                 .FirstOrDefault() as DescriptionAttribute)?.Description ?? e.ToString();
      }
    }
    
    [ValueConversion(typeof(Enum), typeof(IEnumerable))]
    public class EnumToCollectionConverter : MarkupExtension, IValueConverter
    {
      public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
      {
        return Enum.GetValues(value.GetType())
                   .Cast()
                   .Select(e => new ValueDescription() { Value = e, Description = e.Description()})
                   .ToList();
      }
      public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
      {
        return null;
      }
      public override object ProvideValue(IServiceProvider serviceProvider)
      {
        return this;
      }
    }
    

    This converter will work with any enum. ValueDescription is just a simple class with a Value property and a Description property. You could just as easily use a Tuple with Item1 and Item2, or a KeyValuePair with Key and Value instead of Value and Description or any other class of your choice as long as it has can hold an enum value and string description of that enum value.

提交回复
热议问题