Hiding unwanted properties in custom controls

前端 未结 5 1051
一向
一向 2020-11-27 22:53

Is this the way to hide properties in derived controls?

public class NewButton : Button

...

[Browsable ( false )]
public new Con         


        
相关标签:
5条回答
  • 2020-11-27 23:13

    From code, the closest you can do it to hide it, and perhaps make it a pain to call directly - note that even when hidden it is callable, and none of this will work past a cast:

    // about the closest you can do, but not really an answer
    [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
    [Obsolete("just cast me to avoid all this hiding...", true)]
    public new ContentAlignment TextAlign { get; set; }
    

    Personally, I wouldn't bother. It isn't robust (just cast).

    0 讨论(0)
  • 2020-11-27 23:13

    Maybe what you want to do is derive from ContainerControl or UserControl, add a Button to that control and just expose those parts of the Button interface you want to keep.

    0 讨论(0)
  • 2020-11-27 23:16

    Why don't you make it private? It guarantees that ancestors will not see it. Edit: In this case you have to inherit a new class from the base and use your new class, which now hides ths property.

    public class MyTextBox: TextBox
    {
    ...
            private new ContentAlignment TextAlign
            {
              get { return base.ContentAlignment; }
              set { base.ContentAlignment = value; }
            }
    }
    
    0 讨论(0)
  • 2020-11-27 23:17

    No, you can remove them from the designer (as shown) but you cannot really hide them form code as that would violate the substitution principle. It has been asked & answered many times here, see for example this SO question.

    0 讨论(0)
  • 2020-11-27 23:29

    You can use the [EditorBrowsable] attribute, as documented here.

    [EditorBrowsable(EditorBrowsableState.Never)]
    public bool HideMeInIntellisense
    {
        // ...
    

    From the documentation:

    ...the IntelliSense engine in Visual Studio uses this attribute to determine whether to show a property or method.

    However, users can override this in VS settings. ReSharper also has a setting that controls whether this attribute is honoured in its IntelliSense.

    Out of curiousity, why do you want to hide something from users? Just because a member is hidden in the way described above doesn't mean you couldn't use it in code and compile it successfully. It just inhibits the discoverability of the member.

    0 讨论(0)
提交回复
热议问题