基本思想是使用自定义类型描述符,因为它已经在 Marc 的回答中得到解决。您可以在我的帖子中看到一个实现。通过更改 ShouldSerializeValue 的覆盖并返回 false,您可以轻松地使链接的帖子为您工作。就这样。
但在这里我想分享另一个选择,一个更短的答案,它需要更少的努力,但基本上为你做同样的事情。将对象传递给 PropertyGrid 时使用代理:
假设您有一个像这样的通用类:
public class MyClass
{
public string MyProperty1 { get; set; }
public string MyProperty2 { get; set; }
public string MyProperty3 { get; set; }
}
这是您使用代理的方式:
var myOriginalObject = new MyClass();
this.propertyGrid1.SelectedObject = new ObjectProxy(myOriginalObject);
这是更改属性后的结果:

这ObjectProxy
是一个派生的类,CustomTypeDescriptor
将为您带来神奇的效果。这是课程:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
public class ObjectProxy : CustomTypeDescriptor
{
public object Original { get; private set; }
public List<string> BrowsableProperties { get; private set; }
public ObjectProxy(object o)
: base(TypeDescriptor.GetProvider(o).GetTypeDescriptor(o)) => Original = o;
public override PropertyDescriptorCollection GetProperties(Attribute[] a)
{
var props = base.GetProperties(a).Cast<PropertyDescriptor>()
.Select(p => new MyPropertyDescriptor(p));
return new PropertyDescriptorCollection(props.ToArray());
}
public override object GetPropertyOwner(PropertyDescriptor pd) => Original;
}
public class MyPropertyDescriptor : PropertyDescriptor
{
PropertyDescriptor o;
public MyPropertyDescriptor(PropertyDescriptor originalProperty)
: base(originalProperty) => o = originalProperty;
public override bool CanResetValue(object c) => o.CanResetValue(c);
public override object GetValue(object c) => o.GetValue(c);
public override void ResetValue(object c) => o.ResetValue(c);
public override void SetValue(object c, object v) => o.SetValue(c, v);
public override bool ShouldSerializeValue(object c) => false;
public override AttributeCollection Attributes => o.Attributes;
public override Type ComponentType => o.ComponentType;
public override bool IsReadOnly => o.IsReadOnly;
public override Type PropertyType => o.PropertyType;
}