2009-08-10 87 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