PropertyGrid:隐藏基类属性,怎么样?

时间:2011-08-14 01:32:01

标签: c# propertygrid

PropertyGrid ...对于用户我想只留下其中几个。但是现在我看到了所有内容,当看到像Dock或Cursor这样的东西时,用户会感到困惑...... 希望现在很清楚......

2 个答案:

答案 0 :(得分:10)

使用此属性:

[Browsable(false)]
public bool AProperty {...} 

对于继承的属性:

[Browsable(false)]
public override bool AProperty {...} 

另一个想法(因为你试图隐藏所有基类成员):

public class MyCtrl : TextBox
{
  private ExtraProperties _extraProps = new ExtraProperties();

  public ExtraProperties ExtraProperties
  {
    get { return _extraProps; }
    set { _extraProps = value; }
  }
}

public class ExtraProperties
{
  private string _PropertyA = string.Empty;

  [Category("Text Properties"), Description("Value for Property A")]
  public string PropertyA {get; set;}

  [Category("Text Properties"), Description("Value for Property B")]
  public string PropertyB { get; set; }
}

然后是属性网格:

  MyCtrl tx = new MyCtrl();
  pg1.SelectedObject = tx.ExtraProperties;

缺点是它会改变您对

的属性的访问级别
tx.PropertyA = "foo";

tx.ExtraProperties.PropertyA = "foo";

答案 1 :(得分:7)

要隐藏MyCtrl属性,请在属性上使用[Browsable(False)]属性。

[Browsable(false)]
public bool AProperty { get; set;}

要隐藏 继承的 项目,您需要覆盖基础并应用可浏览属性。

[Browsable(false)]
public override string InheritedProperty  { get; set;}

注意: 您可能需要根据具体情况添加virtualnew关键字。

更好的方法是使用ControlDesigner。设计器有一个名为PreFilterProperties的覆盖,可用于向PropertyGrid提取的集合添加额外的属性。

Designer(typeof(MyControlDesigner))]
public class MyControl : TextBox
{
    // ...
}

public class MyControlDesigner : ...
{
    // ...

    protected override void PreFilterProperties(
                             IDictionary properties) 
    {
        base.PreFilterProperties (properties);

        // add the names of proeprties you wish to hide
        string[] propertiesToHide = 
                     {"MyProperty", "ErrorMessage"};  

        foreach(string propname in propertiesToHide)
        {
            prop = 
              (PropertyDescriptor)properties[propname];
            if(prop!=null)
            {
                AttributeCollection runtimeAttributes = 
                                           prop.Attributes;
                // make a copy of the original attributes 

                // but make room for one extra attribute

                Attribute[] attrs = 
                   new Attribute[runtimeAttributes.Count + 1];
                runtimeAttributes.CopyTo(attrs, 0);
                attrs[runtimeAttributes.Count] = 
                                new BrowsableAttribute(false);
                prop = 
                 TypeDescriptor.CreateProperty(this.GetType(), 
                             propname, prop.PropertyType,attrs);
                properties[propname] = prop;
            }            
        }
    }
}

您可以将要隐藏的proeprties名称添加到propertiesToHide,以便更清晰地分离。

到期时:http://www.codeproject.com/KB/webforms/HidingProperties.aspx#