C# .Net 4.5 PropertyGrid:如何隐藏属性



问题很简单(我希望这有一个简单的解决方案!):我想隐藏(可浏览(false))属性"元素"(在我的PropertyGrid对象中)当它为零时。

    public class Question
    {
       ...
      public int Element
      {
        get; set;
      }
    }

对我来说,在 PropertGrid 和自定义控件中隐藏属性的最简单方法是:

public class Question
{
   ...
  
  [Browsable(false)]
  public int Element
  {
    get; set;
  }
}

要动态执行此操作,您可以使用以下代码,其中 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);
            }
          }
   }
}

你可以做的是重用我在SO上回答这个问题时描述的DynamicTypeDescriptor类:找不到实体框架创建的属性的PropertyGrid可浏览,如何找到它?

例如,像这样:

public Form1()
{
    InitializeComponent();
    DynamicTypeDescriptor dt = new DynamicTypeDescriptor(typeof(Question));
    Question q = new Question(); // initialize question the way you want    
    if (q.Element == 0)
    {
        dt.RemoveProperty("Element");
    }
    propertyGrid1.SelectedObject = dt.FromComponent(q);
}

尝试 BrowsableAttributes/BrowsableProperties 和 HiddenAttributes/HiddenProperties:

更多信息在这里

当我多年前想解决这个问题时,我记得,属性 [可浏览] 不起作用。我看到它现在工作得很好,但我也通过创建代理对象的方式制定了解决方案。

有代码:https://github.com/NightmareZ/PropertyProxy

您可以使用属性突出显示所需的属性,然后创建代理对象,该对象将仅将突出显示的属性转发到 PropertyGrid 控件。

public class Question
{
   ...
  
  [PropertyProxy]
  public int Element
  {
    get; set;
  }
}
...
var factory = new PropertyProxyFactory();
var question = new Question();
var proxy = factory.CreateProxy(question);
propertyGrid.SelectedObject = proxy;

最新更新