Converter to show description of an enum, and convert back to enum value on selecting an item from combo box in wpf

后端 未结 5 1110
耶瑟儿~
耶瑟儿~ 2020-12-15 08:13

I am using an enum to enlist values in my combobox. I want to write a converter that would show the "description" of the selected enum value. And, when selected, i

5条回答
  •  囚心锁ツ
    2020-12-15 08:38

    Supplement to the above examples to show decorating the enum with attributes.

    sealed class DescriptionAttribute : Attribute
    {
        readonly string description;
    
        public DescriptionAttribute(string description)
        {
            this.description = description;
        }
    
        public string Description
        {
            get { return description; }
        }
    }
    
    enum Vehicle
    {
        [Description("Benz")]
        Car,
        [Description("Volvo")]
        Bus,
        [Description("Honda")]
        Bike
    }
    

    BTW, I wonder why you needed to convert back the description to enum. If you provide the enums itself as ItemSource, you can use the description technique to show the display value in the ComboBox, however, once an item is selected you can directly have an enum as selected item.

提交回复
热议问题