我有一个PropertyGrid,可显示对象的所有实例属性。有没有办法在相同或单独的PropertyGrid中显示对象所属类的静态属性?另外,还有另一个Forms控件可以让我执行此操作吗?
答案 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);