【发布时间】:2021-10-18 15:00:30
【问题描述】:
我的 winforms 应用程序中有一个 PropertyGrid,它显示了一些选定对象的属性。我希望有时会显示某个属性,而有时则不会,由我选择,(假设每次在运行时按下特定按钮时,可浏览性都会发生变化)。 在运行前设置可浏览性非常容易,使用 BrowsableAttribute,据我了解,属性是在设计时设置的,因此我需要另一个解决方案。 在很多地方我都找到了这段代码:
public static void ChangeBrowsability(SomeObject obj, string propertyName, bool isBrowsable)
{//usage: supposed to change browsability at runtime
PropertyDescriptor descriptor = TypeDescriptor.GetProperties(obj)[propertyName];
BrowsableAttribute attrib = (BrowsableAttribute)descriptor.Attributes[typeof(BrowsableAttribute)];
FieldInfo browsableField = attrib.GetType().GetField("browsable", BindingFlags.NonPublic | BindingFlags.Instance);
browsableField.SetValue(attrib, isBrowsable);
}
第一个问题是 browsableField 出于某种原因总是为空,我想知道为什么。
也欢迎使用此代码的替代解决方案。
【问题讨论】:
-
属性信息存储在元数据中,并在编译时编译到程序集中
-
您可以为您的类实现一个 TypeConverter 并通过覆盖 GetProperties 方法返回您想要的任何属性。您不必使用 BrowsableAttribute。你可以得到一些提示here。