0

C# プロパティ グリッドについて質問があります。

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

しかし、それはエラーを引き起こします。

4

1 に答える 1

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

これを試してみてください....

于 2014-08-05T12:44:39.647 に答える