我在我的应用程序中使用 PropertyGrid。我需要在运行时根据自定义数据标准更改某些属性的可见性和只读性。
虽然我没有找到简单的东西并准备好,但我找到了一种解决方法,方法是在运行时更改ReadOnlyAttribute
andBrowsableAttribute
属性,如下所示:
protected void SetBrowsable(string propertyName, bool value)
{
PropertyDescriptor property = TypeDescriptor.GetProperties(GetType())[propertyName];
BrowsableAttribute att = (BrowsableAttribute)property.Attributes[typeof(BrowsableAttribute)];
FieldInfo cat = att.GetType().GetField("browsable", BindingFlags.NonPublic | BindingFlags.Instance);
if (property.Attributes.Cast<Attribute>().Any(p => p.GetType() == typeof(BrowsableAttribute)))
cat.SetValue(att, value);
}
protected void SetReadOnly(string propertyName, bool value)
{
PropertyDescriptor property = TypeDescriptor.GetProperties(GetType())[propertyName];
ReadOnlyAttribute att = (ReadOnlyAttribute)property.Attributes[typeof(ReadOnlyAttribute)];
FieldInfo cat = att.GetType().GetField("isReadOnly", BindingFlags.NonPublic | BindingFlags.Instance);
if (property.Attributes.Cast<Attribute>().Any(p => p.GetType() == typeof(ReadOnlyAttribute)))
cat.SetValue(att, value);
}
现在,我的问题是我应该在哪里调用这些方法?有什么我可以处理的事件object
来调用这些方法吗?也许通过实现一个接口。