当对象设置为PropertyGrid.SelectObject的对象时,可使用下面的方法隐藏部分属性:
void SetPropertyVisible(object obj, string propertyName, bool visibles){
Type type = typeof(System.ComponentModel.BrowsableAttribute);
PropertyDescriptor propDesc = TypeDescriptor.GetProperties(obj)[propertyName];
Attribute attr = propDesc.Attributes[type];
FieldInfo fieldInfo = type.GetField("browsable", BindingFlags.Instance BindingFlags.NonPublic);
fieldInfo.SetValue(attr, visible);
}
需要注意的是,定义类属性时,要将所有的属性都标记Browsable属性。
[Browsable(true)]
[ReadOnly(false)]
public string String1{
get { return this.string1; }
set { this.string1 = value; }
}
同样的也可以通过上面的方法设置属性是否只读,只需更改2行代码:
Type type = typeof(System.ComponentModel.ReadOnlyAttribute);
FieldInfo fieldInfo = type.GetField("isReadOnly", BindingFlags.Instance BindingFlags.NonPublic);
No comments:
Post a Comment