How Do I Stop Visual Studio from Generating property setting for the controls in designer?

667 Views Asked by At

In Visual Studio 2008, when I add some controls to form the designer creates some codes regarding the properties of the control automatically. Now, I'm using my own user controls and by adding them to the form, the designer again creates the code lines automatically, in this case the property FONT is one of those that I don't want the designer to add it since it overwrites the font setting in the upper level. Anyone knows how I can set which properties to be set in designer?

1

There are 1 best solutions below

0
On

The designer only adds a line of code changing a property's value if it determines that the value is different from the DefaultValue[Attribute].

If your custom control wants to change what the default value of the Font property is (or any other base-class property), you have to perform a little wizardry:

public class MyControl : Control
{
    public MyControl()
    {
        base.Font = new Font("Arial", 9.75f);
    }

    [DefaultValue(typeof(Font), "Arial, 9.75pt")]
    public new Font Font
    {
        get { return base.Font; }
        set { base.Font = value; }
    }
}

Notice the 'new' keyword on the Font property? Font is not virtual, so you can't override it and we don't want to do that. You override to change behavior. We don't want to alter the behavior (which is why the code simply redirects back to the base), we just want to expose a new DefaultValue. This tricks the designer into considering the new default for your control.

We also make sure that our Font property has that value when it is constructed.