你不能通過配置來做到這一點;但您可以通過編寫自定義組件模型實現來控制屬性;即編寫你自己的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