你不能通过配置来做到这一点;但您可以通过编写自定义组件模型实现来控制属性;即编写你自己的PropertyDescriptor
,并使用ICustomTypeDescriptor
或TypeDescriptionProvider
关联它。很多工作。
更新
我想到了一个狡猾的方式来做到这一点;见下文,我们在运行时使用字符串将其过滤到2个属性。如果你没有自己的类型(设置[TypeConverter]
),那么你可以使用:
TypeDescriptor.AddAttributes(typeof(Test),
new TypeConverterAttribute(typeof(TestConverter)));
到转换器在运行时关联。
using System.Windows.Forms;
using System.ComponentModel;
using System.Collections.Generic;
using System;
class TestConverter : ExpandableObjectConverter
{
public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, System.Attribute[] attributes)
{
PropertyDescriptorCollection orig = base.GetProperties(context, value, attributes);
List<PropertyDescriptor> list = new List<PropertyDescriptor>(orig.Count);
string propsToInclude = "Foo|Blop"; // from config
foreach (string propName in propsToInclude.Split('|'))
{
PropertyDescriptor prop = orig.Find(propName, true);
if (prop != null) list.Add(prop);
}
return new PropertyDescriptorCollection(list.ToArray());
}
}
[TypeConverter(typeof(TestConverter))]
class Test
{
public string Foo { get; set; }
public string Bar { get; set; }
public string Blop { get; set; }
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Test test = new Test { Foo = "foo", Bar = "bar", Blop = "blop"};
using (Form form = new Form())
using (PropertyGrid grid = new PropertyGrid())
{
grid.Dock = DockStyle.Fill;
form.Controls.Add(grid);
grid.SelectedObject = test;
Application.Run(form);
}
}
}
(注意:我更新了我与可能做你最想要的一个例子答案) – 2009-08-10 23:38:51
还看到:http://stackoverflow.com/questions/1093466/c-dynamic-attribute-arguments – 2010-03-27 22:09:12