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

时间:2013-09-20 21:25:06

标签: c# .net properties propertygrid

问题很简单(我希望这有一个简单的解决方案!):我想隐藏(Browsable(false))属性“Element”(在我的PropertyGrid对象中),当它为零时。

    public class Question
    {
       ...

      public int Element
      {
        get; set;
      }
    }

4 个答案:

答案 0 :(得分:20)

在我的PropertyGrid和自定义控件中隐藏属性的最简单方法是:

public class Question
{
   ...

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

答案 1 :(得分:8)

您可以做的是重新使用我在这个问题的答案中描述的DynamicTypeDescriptor课程:PropertyGrid Browsable not found for entity framework created property, how to find it?

就像这样:

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

答案 2 :(得分:0)

尝试BrowsableAttributes / BrowsableProperties和HiddenAttributes / HiddenProperties:

More info here

答案 3 :(得分:0)

许多年前,当我想解决此问题时,[Browsable]属性不起作用。我看到它现在很好用,但是我也通过创建代理对象来提出解决方案。

有代码: 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;