在PropertyGrid中绑定Enum集合

时间:2015-02-03 15:27:08

标签: c# propertygrid

我有以下枚举。

public enum Digits
{One, Two, Three}

以及包含两个条目的属性。

public List<Digits> DigitList{get;set;}
DigitList.Add(Digits.One); DigitList.Add(Digits.Three);

当此对象绑定到PropertyGrid时,它将显示为(Collection),当它打开时(使用小浏览按钮),将显示带有(无有用消息)的异常。我很困惑PropertyGrid如何解释枚举列表。 我搜索了一个解决方案,但我能找到的只是关于如何绑定枚举值,而不是枚举列表。

1 个答案:

答案 0 :(得分:0)

您必须创建一个TypeConverter类,以帮助PropertyEditor将Enum解析为PropertyEditor。

示例TypeConverter

public class FooDataTypeConverter : TypeConverter
{
    public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
    {
        return true;
    }

    public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
    {
        return base.GetStandardValues(context);
    }

    public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
    {
        if (sourceType == typeof(string))
            return true;

        return (sourceType.Equals(typeof(Enum)));
    }

    public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
    {
        return (destinationType.Equals(typeof(String)));
    }

    public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
    {
        if (value is string)
        {
            return (ValidationDataType)Enum.Parse(typeof(ValidationDataType), value.ToString(), true);
        }

        return base.ConvertFrom(context, culture, value);
    }

    public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
    {
        if (!destinationType.Equals(typeof(string)))
            throw new ArgumentException("Can only convert to string", "destinationType");

        if (!value.GetType().BaseType.Equals(typeof(Enum)))
            throw new ArgumentException("Can only convert an instance of enum", "value");

        string name = value.ToString();
        object[] attr =
            value.GetType().GetField(name).GetCustomAttributes(typeof(DescriptionAttribute), false);

        return (attr.Length > 0) ? ((DescriptionAttribute)attr[0]).Description : name;

    }

}

将此声明添加到要在属性编辑器中解析的枚举后。

    [TypeConverter(typeof(FooDataTypeConverter ))]
    public enum ValidationDataType
    {
        /// <summary>
        /// None
        /// </summary>
        [Description("None")]
        None,

       .....
}

最后一步是将它添加到将在属性编辑器中显示的组件属性

[Category("Behavior")]
[Description("Gets or sets the type of data that will be compared")]
[TypeConverter(typeof(DataTypeConverter))]
[EditorAttribute(typeof(ValidatorTypeEditor), typeof(System.Drawing.Design.UITypeEditor))]
public ValidationDataType Type
{
    get { return this.type; }
    set 
    { 
        this.type = value;
        if (this is RangeValidator)
        {
            this.SetRange();
        }
    }
}