【发布时间】:2010-09-23 18:01:40
【问题描述】:
如何在运行时以各种方式修改属性网格?我希望能够添加和删除属性并添加“动态类型”,我的意思是这种类型会导致使用 TypeConverter 在 propertygrid 中生成运行时下拉列表。
我实际上已经能够做这两件事(添加/删除属性和添加动态类型),但不能同时做。
为了实现在运行时添加和删除属性的支持,我使用了this codeproject article 并稍微修改了代码以支持不同的类型(不仅仅是字符串)。
private System.Windows.Forms.PropertyGrid propertyGrid1;
private CustomClass myProperties = new CustomClass();
public Form1()
{
InitializeComponent();
myProperties.Add(new CustomProperty("Name", "Sven", typeof(string), false, true));
myProperties.Add(new CustomProperty("MyBool", "True", typeof(bool), false, true));
myProperties.Add(new CustomProperty("CaptionPosition", "Top", typeof(CaptionPosition), false, true));
myProperties.Add(new CustomProperty("Custom", "", typeof(StatesList), false, true)); //<-- doesn't work
}
/// <summary>
/// CustomClass (Which is binding to property grid)
/// </summary>
public class CustomClass: CollectionBase,ICustomTypeDescriptor
{
/// <summary>
/// Add CustomProperty to Collectionbase List
/// </summary>
/// <param name="Value"></param>
public void Add(CustomProperty Value)
{
base.List.Add(Value);
}
/// <summary>
/// Remove item from List
/// </summary>
/// <param name="Name"></param>
public void Remove(string Name)
{
foreach(CustomProperty prop in base.List)
{
if(prop.Name == Name)
{
base.List.Remove(prop);
return;
}
}
}
等等……
public enum CaptionPosition
{
Top,
Left
}
我的完整解决方案可以下载here。
当我添加字符串、布尔值或枚举时,它可以正常工作,但是当我尝试添加像 StatesList 这样的“动态类型”时,它就不起作用了。有谁知道为什么,可以帮我解决吗?
public class StatesList : System.ComponentModel.StringConverter
{
private string[] _States = { "Alabama", "Alaska", "Arizona", "Arkansas" };
public override System.ComponentModel.TypeConverter.StandardValuesCollection
GetStandardValues(ITypeDescriptorContext context)
{
return new StandardValuesCollection(_States);
}
public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
{
return true;
}
public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
{
return true;
}
}
当您不尝试在运行时添加属性时,使用 TypeConverter 的方法可以正常工作,例如 this code 可以正常工作,但我希望能够同时做到这两个。
请查看my project。 谢谢!
【问题讨论】:
标签: c# .net winforms propertygrid