我想在属性网格中显示所选值的字符串下拉列表。 在我当前的情况下,我必须将字典对象绑定(bind)到属性网格。
如果我要绑定(bind)一个类,可以使用 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;
}
结果看起来像这样。
如果我绑定(bind)到字典,有什么建议如何显示此下拉列表吗?我用过this code将字典绑定(bind)到 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;
}
最佳答案
这相对容易。
这个想法是允许为自定义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
与您的“属性”关联起来,类似于对这样的类所做的操作:
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;
}
结果将是:
您还可以关联其他属性,例如 DisplayName
、Category
等。
关于c# - 如何在绑定(bind)到字典的 Propertygrid 中显示下拉菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36195452/