我对c#property grid有疑问。
public enum xxx
{
[Browsable(true)]
aaa,
[Browsable(false)]
bbb,
[Browsable(true)]
ccc,
}
public class testObject {
public xxx temp;
public xxx test {
get { return temp; }
set { temp = value; }
}
如何在运行时更改可浏览属性?
例如,当按下btn1时,我想为所有人设置browsable属性为false,如下所示:
private void button1_Click(object sender, RoutedEventArgs e)
{
object[] browsable;
Type type = typeof(xxx);
FieldInfo[] fieldInfos = type.GetFields();
foreach (FieldInfo fieldInfo in fieldInfos)
{
browsable = fieldInfo.GetCustomAttributes(typeof(BrowsableAttribute), false);
if (browsable.Length == 1)
{
BrowsableAttribute brAttr = (BrowsableAttribute)browsable[0];
fieldInfo.SetValue(brAttr, false);
}
}
}
但它会导致错误。
答案 0 :(得分:1)
你可以用这种方式改变可浏览的财产......
object[] browsable;
Type type = typeof(xxx);
FieldInfo[] fieldInfos = type.GetFields();
foreach (FieldInfo fieldInfo in fieldInfos)
{
browsable = fieldInfo.GetCustomAttributes(typeof(BrowsableAttribute), false);
if (browsable.Length == 1)
{
System.ComponentModel.PropertyDescriptorCollection pdc = System.ComponentModel.TypeDescriptor.GetProperties(fieldInfo);
//Get property descriptor for current property
System.ComponentModel.PropertyDescriptor descriptor = pdc[24];// custom attribute
BrowsableAttribute attrib =
(BrowsableAttribute)descriptor.Attributes[typeof(BrowsableAttribute)];
FieldInfo isReadOnly =
attrib.GetType().GetField("browsable", BindingFlags.NonPublic | BindingFlags.Instance);
isReadOnly.SetValue(attrib, true);
}
}
尝试这个可能对你有帮助....