Felix
Felix

Reputation: 1016

Is it possible to override a winform panel's padding in c#?

I have a very simple problem but I have yet to find a simple soultion.

I'm creating a custom panel that has a border and rounded corners. I'd like to be able to override the padding, so whatever the user puts, I'll add some value to it so it won't overlap with the border.I'd like to be able to do this both in runtime and in design time. So for exemple if I dock a control such as a PictureBox inside my panel, it won't draw over the borders.

I've tried to simply override the padding property, but I get the following error:

cannot override inherited member 'System.Windows.Forms.Control.Padding.set' because it is not marked virtual, abstract, or override
Anyone have a (simple) workaround for this?

Upvotes: 2

Views: 2722

Answers (2)

Hans Passant
Hans Passant

Reputation: 941635

Well, the Padding property is not virtual so trying to override it simply can't work. You'll have to replace the property. That requires using the new keyword, an often very troublesome way fix inheritance problems. But it works well for Winforms controls since the designer only ever uses the actual instance of the control, Winforms itself doesn't use the setter and client code very rarely uses the base class to call the setter.

So this will almost always work just fine:

class MyControl : Control {
    public new Padding Padding {
        get { return base.Padding; }
        set {
            // override value
            //...
            base.Padding = value;
        }
    }
}

Upvotes: 3

Felix
Felix

Reputation: 1016

The best I could come up with was this:

     protected override void OnPaddingChanged(EventArgs e)
    {
        base.OnPaddingChanged(e);
        if (Padding.Left < 3)
        {
            base.Padding = new Padding(3, base.Padding.Top, base.Padding.Right, base.Padding.Bottom);
        }
        if (Padding.Top < 3)
        {
            base.Padding = new Padding(base.Padding.Left, 3, base.Padding.Right, base.Padding.Bottom);
        }
        if (Padding.Right < 3)
        {
            base.Padding = new Padding(base.Padding.Left, base.Padding.Top, 4, base.Padding.Bottom);
        }
        if (Padding.Bottom < 3)
        {
            base.Padding = new Padding(base.Padding.Left, base.Padding.Top, base.Padding.Right, 3);
        }
    }

It works at design time and run time, I don't know if it's any good but it works for what I have to do.

Upvotes: 0

Related Questions