7

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

    public class Question
    {
       ...

      public int Element
      {
        get; set;
      }
    }
4

4 回答 4

29

对我来说,在 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);
            }
          }
   }
}
于 2014-07-22T14:31:49.970 回答
9

您可以做的是重用DynamicTypeDescriptor我在此处对这个问题的回答中描述的类 SO: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);
}
于 2013-09-22T10:35:15.920 回答
0

试试 BrowsableAttributes/BrowsableProperties 和 HiddenAttributes/HiddenProperties:

更多信息在这里

于 2013-09-20T21:35:43.347 回答
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;
于 2020-07-23T13:41:59.120 回答