【问题标题】:.NET Property Grid - setting Browsable (bool) using App.config.NET 属性网格 - 使用 App.config 设置 Browsable (bool)
【发布时间】:2009-08-10 21:56:02
【问题描述】:

我希望能够使用 App.config 在我的属性网格上设置属性的可见性。我试过了:

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

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

【问题讨论】:

标签: c# configuration settings propertygrid browsable


【解决方案1】:

您不能在 app.config 中执行上述操作。这是基于设计时的,您的 app.config 会在运行时读取和使用。

【讨论】:

    【解决方案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);
            }
        }
    }
    

    【讨论】:

    • 这是关于该主题的非常有根据的答案。使用 ICustomTypeDescriptor 或与之关联的其他类型(查看 MSDN 以了解最适合您的设计的类型),您可以使用配置值初始化描述符,但您必须手动完成工作(如配置;请参阅 System.Configuration.ConfigurationSection 和类似的)作为默认类型描述符使用在编译时应用于程序集类型信息的属性。
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 2013-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-19
      • 2011-11-05
      • 2012-01-18
      相关资源
      最近更新 更多