Databinding an enum property to a ComboBox in WPF

后端 未结 13 1377
北海茫月
北海茫月 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:38

    You can create a custom markup extension.

    Example of usage:

    enum Status
    {
        [Description("Available.")]
        Available,
        [Description("Not here right now.")]
        Away,
        [Description("I don't have time right now.")]
        Busy
    }
    

    At the top of your XAML:

        xmlns:my="clr-namespace:namespace_to_enumeration_extension_class
    

    and then...

    <ComboBox 
        ItemsSource="{Binding Source={my:Enumeration {x:Type my:Status}}}" 
        DisplayMemberPath="Description" 
        SelectedValue="{Binding CurrentStatus}"  
        SelectedValuePath="Value"  /> 
    

    And the implementation...

    public class EnumerationExtension : MarkupExtension
      {
        private Type _enumType;
    
    
        public EnumerationExtension(Type enumType)
        {
          if (enumType == null)
            throw new ArgumentNullException("enumType");
    
          EnumType = enumType;
        }
    
        public Type EnumType
        {
          get { return _enumType; }
          private set
          {
            if (_enumType == value)
              return;
    
            var enumType = Nullable.GetUnderlyingType(value) ?? value;
    
            if (enumType.IsEnum == false)
              throw new ArgumentException("Type must be an Enum.");
    
            _enumType = value;
          }
        }
    
        public override object ProvideValue(IServiceProvider serviceProvider)
        {
          var enumValues = Enum.GetValues(EnumType);
    
          return (
            from object enumValue in enumValues
            select new EnumerationMember{
              Value = enumValue,
              Description = GetDescription(enumValue)
            }).ToArray();
        }
    
        private string GetDescription(object enumValue)
        {
          var descriptionAttribute = EnumType
            .GetField(enumValue.ToString())
            .GetCustomAttributes(typeof (DescriptionAttribute), false)
            .FirstOrDefault() as DescriptionAttribute;
    
    
          return descriptionAttribute != null
            ? descriptionAttribute.Description
            : enumValue.ToString();
        }
    
        public class EnumerationMember
        {
          public string Description { get; set; }
          public object Value { get; set; }
        }
      }
    
    0 讨论(0)
提交回复
热议问题