今天用了一个PropertyGrid的控件,想实现动态的改变其中属性的可见性,在网上查了好久,最后经国宝同志的指点,终于查到了,先记录下来。
PropertyGrid的使用方法:
新建一个类作为显示属性的对象
[DefaultPropertyAttribute("Name")]
public class C
{
private string a ="";
[DisplayNameAttribute("a"), ReadOnlyAttribute(true), CategoryAttribute("b"), DescriptionAttribute("c"), Browsable(true)]
public string A
{
get
{
return a;
}
set
{
a = value;
}
}
}
给PropertyGrid的SelectedObject赋值
propertyGridSummary.SelectedObject = new C();
便行了。
控制属性窗口中A的显示与否:
首先是下面这个函数,其实这个函数很早就查到了,但是用起就是不对。因为一用它就让所有的属性显示或者不显示,不能单独的控制一个。
/// <summary>
/// 设置指定对象的属性可见性
/// </summary>
/// <param name="target">要改变属性可见性的对象</param>
/// <param name="propertyName">要改变的属性</param>
/// <param name="visible">是否可见</param>
private void SetPropertyVisible(object target, string propertyName, bool visible)
{
PropertyDescriptorCollection pdc = TypeDescriptor.GetProperties(target);
PropertyDescriptor property = pdc[propertyName];
if (property != null)
{
AttributeCollection ac = property.Attributes;
Attribute attr = (BrowsableAttribute)ac[typeof(BrowsableAttribute)];
Type attrType = attr.GetType();
FieldInfo fld = attrType.GetField("browsable", BindingFlags.Instance|BindingFlags.NonPublic);
fld.SetValue(attr, visible);
}
}
最后国宝说BrowsableAttribute这种叫特性,我才查到:
使用这个函数的前提是每个属性都要加[Browsable(true)]或者[Browsable(false)]