c#属性网格,将可浏览属性设置为在运行时枚举每个项目

本文关键字:属性 运行时 枚举 项目 设置 网格 浏览 | 更新日期: 2023-09-27 18:16:22

我有一个关于c#属性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);
        }
    }
} 

但是会导致错误

c#属性网格,将可浏览属性设置为在运行时枚举每个项目

你可以通过这种方式改变可浏览属性…

 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);
    }
}

试试这个,这可能会帮助你....