如何在Propertygrid绑定到Dictionary中显示Dropdown

时间:2016-03-24 07:55:42

标签: c# propertygrid

我想在属性网格中显示所选值的字符串下拉列表。 在我目前的情况下,我必须将字典对象绑定到属性网格。

如果我绑定一个类,使用TypeConverter可以很容易地执行以下操作。

public class Employee
{
    public string Name { get; set; }
    [TypeConverter(typeof(JobCategoryConverter))]
    public int? Category { get; set; }        
}

private void Form1_Load(object sender, EventArgs e)
{
    Employee emp = new Employee() {Name = "Ray" ,Category = 1 };
    propertyGrid1.SelectedObject = emp;
}

结果看起来像这样。

enter image description here

如果我绑定到字典,我有什么建议如何显示此下拉列表?我使用this code将字典绑定到propertygrid。

所以代码看起来像,

private void Form1_Load(object sender, EventArgs e)
{
    IDictionary dict = new Hashtable();
    dict["Name"] = "Ray";
    dict["Category"] = 1;

    DictionaryPropertyGridAdapter dpg = new     DictionaryPropertyGridAdapter(dict);
    propertyGrid1.SelectedObject = dpg;
}

1 个答案:

答案 0 :(得分:2)

这相对容易。

我们的想法是允许为自定义DictionaryPropertyDescriptor指定属性。

首先,将DictionaryPropertyDescriptor类构造函数更改为:

internal DictionaryPropertyDescriptor(IDictionary d, object key, Attribute[] attributes)
    : base(key.ToString(), attributes)
{
    _dictionary = d;
    _key = key;
}

然后将以下内容添加到DictionaryPropertyGridAdapter类:

public Dictionary<string, Attribute[]> PropertyAttributes;

并将GetProperties方法更改为:

public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{
    ArrayList properties = new ArrayList();
    foreach (DictionaryEntry e in _dictionary)
    {
        Attribute[] attrs;
        if (PropertyAttributes == null || !PropertyAttributes.TryGetValue(e.Key.ToString(), out attrs))
            attrs = null;
        properties.Add(new DictionaryPropertyDescriptor(_dictionary, e.Key, attrs));
    }

    PropertyDescriptor[] props =
        (PropertyDescriptor[])properties.ToArray(typeof(PropertyDescriptor));

    return new PropertyDescriptorCollection(props);
}

您已完成所需的更改。

现在,您可以将TypeConverter与您的&#34;属性&#34;相关联。类似于你对这样的类做的事情:

enum JobCategory { Accountant = 1, Engineer, Manager }

class JobCategoryConverter : EnumConverter
{
    public JobCategoryConverter() : base(typeof(JobCategory)) { }
}

private void Form1_Load(object sender, EventArgs e)
{
    IDictionary dict = new Hashtable();
    dict["Name"] = "Ray";
    dict["Category"] = 1;

    DictionaryPropertyGridAdapter dpg = new DictionaryPropertyGridAdapter(dict);
    dpg.PropertyAttributes = new Dictionary<string, Attribute[]>
    {
        { "Category", new Attribute[] { new TypeConverterAttribute(typeof(JobCategoryConverter)) } }
    };
    propertyGrid1.SelectedObject = dpg;
}

,结果将是:

enter image description here

您还可以关联其他属性,例如DisplayNameCategory等。