2009-08-10 86 views
1

我想能够使用App.config设置属性在我的属性网格上的可见性。我曾尝试:.NET属性网格 - 使用App.config设置Browsable(布尔)

[Browsable(bool.Parse(Sytem.Configuration.ConfigurationSettings.AppSettings["testBool"]))]

但是Visual Studio 2008中会给我一个错误“的属性参数必须是常量表达式的typeof属性参数类型的表达式或数组创建表达式”。 有什么办法可以在App.config上设置这个布尔值?

+0

(注意:我更新了我与可能做你最想要的一个例子答案) – 2009-08-10 23:38:51

+0

还看到:http://stackoverflow.com/questions/1093466/c-dynamic-attribute-arguments – 2010-03-27 22:09:12

回答

2

你不能在app.config中进行上述操作。这是基于设计时间的,并且您的app.config在运行时被读取和使用。

1

属性网格使用反射来确定要显示的属性以及如何显示它们。你不能在任何类型的配置文件中设置它。您需要将此属性应用于类本身中的属性。

2

你不能通过配置来做到这一点;但您可以通过编写自定义组件模型实现来控制属性;即编写你自己的PropertyDescriptor,并使用ICustomTypeDescriptorTypeDescriptionProvider关联它。很多工作。


更新

我想到了一个狡猾的方式来做到这一点;见下文,我们在运行时使用字符串将其过滤到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); 
     } 
    } 
} 
+0

这是关于这个话题的一个非常有教养的回答。使用ICustomTypeDescriptor或与之关联的其他类型(查看MSDN以查看最适合您的设计的内容),可以使用配置值初始化描述符,但必须手动完成此工作(如配置;请参阅System.Configuration.ConfigurationSection和类似的)作为默认类型描述符使用在编译时应用于组件类型信息的属性。 – TheXenocide 2009-09-04 17:14:07