类型描述符负责提供要在PropertyGrid 中显示的属性列表。
要自定义属性列表,您需要使用以下任一选项为您的类/对象提供自定义类型描述:
示例
在这个例子中,我实现了最后一个选项。我假设您将保持主类不变,只是为了在PropertyGrid 中显示,我创建了一个自定义包装器对象,它提供属性网格的属性列表,包括静态属性。
假设您有这样的课程:
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);