views:

102

answers:

2

I am trying to create a custom command button that defaults width and height to specific settings. I have the following code:

public partial class myCommandButton : Button
{
    public magCommandButton()
    {
        InitializeComponent();

    }

    [DefaultValue(840)]
    public override int Width
    {
        get 
        {
            return base.Width;
        }
        set
        {
            base.Width = value;
        }
    }

    [DefaultValue(340)]
    public override int Height
    {
        get
        {
            return base.Height;
        }
        set
        {
            base.Height = value;
        }
    }

    protected override void OnPaint(PaintEventArgs pe)
    {
        base.OnPaint(pe);
    }
}

However, it won't compile because it tells me that I can not override Width or Height. Can anyone tell me if I'm approaching this wrongly, or if there's a way around this?

A: 

Width and Height are not virtual members (check Control class in Reflector), so the simpliest way is to override DefaultSize property:

        protected override Size DefaultSize
        {
            get
            {
                return new Size(840, 340);
            }
        }

You can also use new modifier, but for this example I recommend to override DefaultSize. If you check Control class in Reflector you will see, that Height and Width use a lot of internal/private members. So I don't that implementing all those things is a good idea. Just use DefaultSize property.

Jarek
You don't necessarly need reflector to check classes methods/definitions/modifiers/etc.You can simply view the class metadata in visual studio by clicking "Go to definition" in the context menu over the word "Control" or whatever type you need to check ;)
digEmAll
Well... I don't like to view metadata only. I'm using resharper + scout plugin and it's great. New reflector has some features and you can go directly to this tool from code and check the implementation, but scout is better I think.But new Resharper (v 5.0) is the best - you can watch compiled assemblies source code directly from VS :D
Jarek
+1  A: 

First, note that the DefaultValueAttribute does not actually set default values! This attribute is only used by the Windows Forms Designer to know if it should display a property in the Properties window with a regular or bold font; if a property has a different value from the argument supplied to DefaultValueAttribute, the property is displayed with a bold font.

In order to set a default size, you can either:

  1. override the DefaultSize property (as shown in @Jarek's answer), or

  2. set the Size property in the constructor (though this solution is not as elegant).

stakx