nr1
nr1

Reputation: 777

C#: PictureBox override Width

How can i override the Width property of a PictureBox? (i need to set the base.Width, but additional to execute a method)

Following isn't working:

public class l33tProgressBar : PictureBox
{
    public override int Width
    {
        get { return this.Width; }
        set
        {
            myMethod();

            base.Width = value;
        }
    }
}

Upvotes: 1

Views: 592

Answers (2)

Adam Lear
Adam Lear

Reputation: 38778

Creating a method for it would probably be cleaner. Hiding a method call in what others would expect to be an inherited property isn't a readable or maintainable approach.

public class l33tProgressBar : PictureBox
{
    public void SetWidthMyWay(int width)
    {
        myMethod();
        this.Width = width;
    }
}

Upvotes: 1

Jamiec
Jamiec

Reputation: 136154

Width is not virtual, so you cant override it. You can however, overwrite it using the new keyword.

public new int Width
{
    get { return base.Width; }
    set
    {
        myMethod();

        base.Width = value;
    }
}

However, a better option might be to override the SizeChanged (docs) event handler instead

public override void OnSizeChanged(EventArgs e)
{
   // Width or Height has been changed
   base.OnSizeChanged(e); // Essential, or event will not be raised!
}

Upvotes: 1

Related Questions