有没有一种方法可以在PropertyGrid中显示静态属性?

时间:2019-05-30 02:17:12

标签: c# winforms properties static propertygrid

我有一个PropertyGrid,可显示对象的所有实例属性。有没有办法在相同或单独的PropertyGrid中显示对象所属类的静态属性?另外,还有另一个Forms控件可以让我执行此操作吗?

1 个答案:

答案 0 :(得分:0)

类型描述符负责提供PropertyGrid的属性列表。要自定义属性列表,您需要为您的类/对象提供自定义类型描述。为此,可以使用以下任一选项:

  • 您的课程可以实现ICustomTypeDescriptor
  • 您的课程可以来自CustomTypeDescriptor
  • 您可以创建一个新的TypeDescriptor并将其注册为您的类或对象实例

示例

假设您有一个这样的课程:

public class MyClass
{
    public string InstanceProperty { get; set; }
    public static string StaticProperty { get; set; } = "Test";
}

您想在PropertyGrid中显示它的属性。

通常,您首先需要的是一个新的属性描述符:

using System;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
public class StaticPropertyDescriptor : PropertyDescriptor
{
    PropertyInfo p;
    Type owenrType;
    public StaticPropertyDescriptor(PropertyInfo pi, Type owenrType)
        : base(pi.Name,
              pi.GetCustomAttributes().Cast<Attribute>().ToArray())
    {
        p = pi;
        this.owenrType = owenrType;
    }
    public override bool CanResetValue(object c) => false;
    public override object GetValue(object c) => p.GetValue(null);
    public override void ResetValue(object c) { }
    public override void SetValue(object c, object v) => p.SetValue(null, v);
    public override bool ShouldSerializeValue(object c) => false;
    public override Type ComponentType { get { return owenrType; } }
    public override bool IsReadOnly { get { return !p.CanWrite; } }
    public override Type PropertyType { get { return p.PropertyType; } }
}

然后,您可以使用我上面提到的任何一个选项。例如,在这里我创建了一个包装器类型描述符,以不影响原始类:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
public class CustomObjectWrapper : CustomTypeDescriptor
{
    public object WrappedObject { get; private set; }
    private IEnumerable<PropertyDescriptor> staticProperties;
    public CustomObjectWrapper(object o)
        : base(TypeDescriptor.GetProvider(o).GetTypeDescriptor(o))
    {
        WrappedObject = o;
    }
    public override PropertyDescriptorCollection GetProperties(Attribute[] attributes)
    {
        var instanceProperties = base.GetProperties(attributes)
            .Cast<PropertyDescriptor>();
        staticProperties = WrappedObject.GetType()
            .GetProperties(BindingFlags.Static | BindingFlags.Public)
            .Select(p => new StaticPropertyDescriptor(p, WrappedObject.GetType()));
        return new PropertyDescriptorCollection(
            instanceProperties.Union(staticProperties).ToArray());
    }
}

使用非常简单:

var myClass = new MyClass();
propertyGrid1.SelectedObject = new CustomObjectWrapper (myClass);

enter image description here