C# PropertyGrid => How to change visible Properties at Runtime

前端 未结 2 1803
野趣味
野趣味 2021-01-28 00:32

I have to following problem,

In a map-editor you can place \"Joints\" (FarseerPhysics) on objects, there are 23 types of joints (in an enum). The joints are all pretty m

2条回答
  •  面向向阳花
    2021-01-28 01:05

    Here is a method for changing the Browsable attribute of a property in your JointItem class:

    private void ChangeBrowsability(object pThis, string pProperty, bool pBrowsable)
    {
        PropertyDescriptor pdDescriptor = TypeDescriptor.GetProperties(pThis.GetType())[pProperty];
        BrowsableAttribute baAttribute = (BrowsableAttribute)pdDescriptor.Attributes[typeof(BrowsableAttribute)];
        FieldInfo fiBrowsable = baAttribute.GetType().GetField("browsable", BindingFlags.NonPublic | BindingFlags.Instance);
        fiBrowsable.SetValue(baAttribute, pBrowsable);
    }
    

    Then you could have a big long if then else sequence or the likes:

    JointItem jiThis = WhereEverYouGetYourJointItemFrom();
    if (jiThis.JointType == eJoinType.Elbow)
    {
        ChangeBrowsability(jiThis, "JointAngle", true);
        ChangeBrowsability(jiThis, "MinAngle", true);
        ChangeBrowsability(jiThis, "MaxAngle", true);
        ChangeBrowsability(jiThis, "ScrewType", false);
        //...
    }
    else ...
    

    Of course you need your dose of "using"s!

    using System.ComponentModel;
    using System.Reflection;
    

提交回复
热议问题