【问题标题】:Hiding elements and categories for custom controls隐藏自定义控件的元素和类别
【发布时间】:2011-06-11 10:44:15
【问题描述】:

我有一个问题。是否可以隐藏基本控件的某些元素和类别(对于自定义控件)。我只想显示我定义的属性。感谢您的宝贵时间。

【问题讨论】:

    标签: c# custom-controls componentmodel


    【解决方案1】:

    隐藏属性并添加[Browsable(false)]

    例如:

    [Browsable(false)]
    public new SomeType SomeProperty {
        get { return base.SomeProperty; }
        set { base.SomeProperty = value; }
    }
    

    【讨论】:

    • 非常感谢,Slaks。做到了。很遗憾,我无法以体面的方式隐藏智能感知的属性。我刚刚发现了工具 -> 选项 -> 文本编辑器 -> C# -> IntelliSense -> 隐藏高级成员。不过,我认为这并不实用,因为它需要控制用户来完成
    【解决方案2】:

    您可以使用[Browsable(false)] 自定义属性来防止该属性出现在 WinForms 属性编辑器中:

    [Browsable(false)]
    public new PropertyType PropertyName
    {
        get { return base.PropertyName; }
        set { base.PropertyName = value; }
    }
    

    但是,这将使该属性仍然有效,只是不会出现在表单设计器中。编译器会很乐意接受它。如果您希望该属性真正停止工作,请抛出异常:

    [Browsable(false)]
    public new PropertyType PropertyName
    {
        get { throw new InvalidOperationException("This property cannot be used with this control."); }
        set { throw new InvalidOperationException("This property cannot be used with this control."); }
    }
    

    当然,编译器会仍然愉快地接受它,但它会在运行时抛出。然而,即便如此,客户端程序员仍然可以通过转换为基本类型来访问“原始”属性,即,而不是

    myControl.PropertyName
    

    他们会写

    ((BaseControlType) myControl).PropertyName
    

    它仍然可以工作。对此您无能为力(只能从不同的基类派生)。

    【讨论】:

    • 其实它会出现在IntelliSense中。
    • @SLaks:很有趣。 BrowsableEditorBrowsable 都不会将其从 IntelliSense 中删除。那么 WinForms 是如何设法从 IntelliSense 中删除 Panel.KeyDown 的呢?
    猜你喜欢
    • 1970-01-01
    • 2011-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-04
    • 1970-01-01
    相关资源
    最近更新 更多