问题很简单(我希望这有一个简单的解决方案!):我想在属性“Element”(在我的 PropertyGrid 对象中)为零时隐藏( Browsable(false) )。
public class Question
{
...
public int Element
{
get; set;
}
}
对我来说,在 PropertGrid 和自定义控件中隐藏属性的最简单方法是:
public class Question
{
...
[Browsable(false)]
public int Element
{
get; set;
}
}
要动态地执行此操作,您可以使用此code,其中 Question 是您的类,您的属性是 Element,因此您可以显示或隐藏它,而无需从集合中删除元素:
PropertyDescriptorCollection propCollection = TypeDescriptor.GetProperties(Question.GetType());
PropertyDescriptor descriptor = propCollection["Element"];
BrowsableAttribute attrib = (BrowsableAttribute)descriptor.Attributes[typeof(BrowsableAttribute)];
FieldInfo isBrow = attrib.GetType().GetField("browsable", BindingFlags.NonPublic | BindingFlags.Instance);
//Condition to Show or Hide set here:
isBrow.SetValue(attrib, true);
propertyGrid1.Refresh(); //Remember to refresh PropertyGrid to reflect your changes
因此,为了完善答案:
public class Question
{
...
private int element;
[Browsable(false)]
public int Element
{
get { return element; }
set {
element = value;
PropertyDescriptorCollection propCollection = TypeDescriptor.GetProperties(Question.GetType());
PropertyDescriptor descriptor = propCollection["Element"];
BrowsableAttribute attrib = (BrowsableAttribute)descriptor.Attributes[typeof(BrowsableAttribute)];
FieldInfo isBrow = attrib.GetType().GetField("browsable", BindingFlags.NonPublic | BindingFlags.Instance);
if(element==0)
{
isBrow.SetValue(attrib, false);
}
else
{
isBrow.SetValue(attrib, true);
}
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)