How to bind a custom Enum description to a DataGrid

前端 未结 1 1810
悲&欢浪女
悲&欢浪女 2021-01-22 03:13

Problem: I have an enumerated type which has description tags in the following style: [URL=\"http://xml.indelv.com/data-binding-enum.html\"]description tag tutorial[/URL] . I ha

相关标签:
1条回答
  • 2021-01-22 03:46

    Wrap them up on the fly and subtly change your handling of the SelectedItem (or whatever you are using)
    My example uses the already present Description attribute.

    public class DescriptiveEnum<T> where T: struct
    {
        private static readonly Dictionary<T,string> descriptions 
            = new Dictionary<T,string>();
    
        static DescriptiveEnum()
        {
            foreach (FieldInfo field in
                typeof(T).GetFields(BindingFlags.Static 
                | BindingFlags.GetField | BindingFlags.Public))
            {
            descriptions.Add((T)field.GetRawConstantValue(),
                LookupName(field));         
            }
        }
    
        public readonly T Value;
    
        public DescriptiveEnum(T value)
        {
            this.Value = value;     
        }
    
        public override string ToString()
        {
            string s;
            if (!descriptions.TryGetValue(this.Value, out s))
            {           
            // fall back for non declared fields
            s = this.Value.ToString();  
            descriptions[this.Value] = s;
            }
            return s;
        }
    
        private static string LookupName(FieldInfo field)        
        {
            object[] all = field.GetCustomAttributes(
                 typeof(DescriptionAttribute), false);
            if (all.Length == 0)
                return field.Name; // fall back
            else
                return ((DescriptionAttribute)all[0])
                    .Description; // only one needed
        }   
    
        public static BindingList<DescriptiveEnum<T>> Make(
            IEnumerable<T> source)
        {
            var list = new BindingList<DescriptiveEnum<T>>();
            foreach (var x in source)
            list.Add(new DescriptiveEnum<T>(x));
            return list;
        }
    }
    

    example usage:

    public enum Foo
    {
        [Description("flibble")]
        Bar,
        [Description("wobble")]
        Baz,
        // none present, will use the name
        Bat
    
    }
    
    Form f = new Form();
    f.Controls.Add(new ListBox() 
    {
        Dock = DockStyle.Fill,
        DataSource = DescriptiveEnum<Foo>.Make(
           new Foo[] { Foo.Bar, Foo.Baz, Foo.Bat }),
    });
    Application.Run(f);
    
    0 讨论(0)
提交回复
热议问题