Data bind enum properties to grid and display description

前端 未结 3 1355
挽巷
挽巷 2020-12-14 04:34

This is a similar question to How to bind a custom Enum description to a DataGrid, but in my case I have multiple properties.

public enum ExpectationResult
{         


        
3条回答
  •  清歌不尽
    2020-12-14 05:16

    I'm not sure how much this helps, but I use an extension method on Enum that looks like this:

        /// 
        /// Returns the value of the description attribute attached to an enum value.
        /// 
        /// 
        /// The text from the System.ComponentModel.DescriptionAttribute associated with the enumeration value.
        /// 
        /// To use this, create an enum and mark its members with a [Description("My Descr")] attribute.
        /// Then when you call this extension method, you will receive "My Descr".
        /// 
        /// 
        /// enum MyEnum {
        ///     [Description("Some Descriptive Text")]
        ///     EnumVal1,
        ///
        ///     [Description("Some More Descriptive Text")]
        ///     EnumVal2
        /// }
        /// 
        /// static void Main(string[] args) {
        ///     Console.PrintLine( MyEnum.EnumVal1.GetDescription() );
        /// }
        /// 
        /// 
        /// This will result in the output "Some Descriptive Text".
        /// 
        public static string GetDescription(this Enum en)
        {
            var type = en.GetType();
            var memInfo = type.GetMember(en.ToString());
    
            if (memInfo != null && memInfo.Length > 0)
            {
                var attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
                if (attrs != null && attrs.Length > 0)
                    return ((DescriptionAttribute)attrs[0]).Description;
            }
            return en.ToString();
        }
    

    You could use a custom property getter on your object to return the name:

    public class TestResult
    {
        public string TestDescription { get; set; }
        public ExpectationResult RequiredExpectationResult { get; set; }
        public ExpectationResult NonRequiredExpectationResult { get; set; }
    
        /* *** added these new property getters *** */
        public string RequiredExpectationResultDescr { get { return this.RequiredExpectationResult.GetDescription(); } }
        public string NonRequiredExpectationResultDescr { get { return this.NonRequiredExpectationResult.GetDescription(); } }
    }
    

    Then bind your grid to the "RequiredExpectationResultDescr" and "NonRequiredExpectationResultDescr" properties.

    That might be a little over-complicated, but its the 1st thing I came up with :)

提交回复
热议问题