我有一个PropertyGrid
显示对象的所有实例属性。有没有办法同时显示对象所属类的静态属性,无论是相同的还是单独的PropertyGrid
?另外,还有另一个Forms控件可以让我执行此操作吗?
类型描述符负责提供要显示的属性列表PropertyGrid
。
要自定义属性列表,您需要使用以下任一选项为您的类/对象提供自定义类型描述:
ICustomTypeDescriptor
CustomTypeDescriptor
TypeDescriptionProvider
为类或对象实例注册一个新的类型描述符来为您的类创建一个类型描述符CustomTypeDescriptor
仅使用for来创建包装对象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);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句