作者热门文章
- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
如何在运行时以各种方式修改属性网格?我希望能够添加和删除属性并添加“动态类型”,我的意思是这种类型会使用 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 .
当我添加字符串、 bool 值或枚举时它工作正常,但是当我尝试添加像 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 .谢谢!
最佳答案
您所做的是将 StatesList(类型转换器)添加为属性。
您应该做的是添加一个属性并将 StatesList 作为其 TypeConverter。
关于c# - 如何在运行时修改 PropertyGrid(添加/删除属性和动态类型/枚举),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/313822/
我是一名优秀的程序员,十分优秀!