简体   繁体   中英

How can I hide some properties for this inherited label?

I have the following code. How can I hide the AutoEllipsis , Image , ImageAlign , ImageIndex , ImageKey , ImageList and TabIndex properties?

Also, how do I set the default size to 50x50px?

public class GradientBox : Label
{
    [DefaultValue(false), Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
    public override bool AutoSize { get; set; }

    [DefaultValue(false), Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
    public override string Text { get; set; }

    [DefaultValue(false), Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
    public override ContentAlignment TextAlign { get; set; }

    // NullRef Exception if use { get; set; }
    [DefaultValue(false), Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
    public override Font Font
    {
        get { return base.Font; }
        set { base.Font = value; }
    }

    public override BorderStyle BorderStyle
    {
        get { return BorderStyle.FixedSingle; }
        set { base.BorderStyle = value; }
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        e.Graphics.FillRectangle(new LinearGradientBrush(new Point(0, 0), new Point(0, this.Height), this.ForeColor, this.BackColor), ClientRectangle);
    }
}

When you inherit from something, your new class needs to be able to behave as if it were the base type (one aspect of polymorphism). That means it can't provide less functionality than the base. So there's no way to remove those properties, because otherwise it wouldn't be a Label .

What you might want to consider is "Composition" instead.

public class GradientBox : Control
{
    private Label myLabel;
    public GradientBox()
    {
        myLabel = new Label;
        // Set your default values
    }


    public Font Font
    {
        get { return myLabel.Font; }
        set { myLabel.Font = value; }
    }
    // repeat to expose just the properties you want.
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM