Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set design-time property default values?

Tags:

c#

.net

winforms

According to MSDN (http://msdn.microsoft.com/en-us/library/system.windows.forms.label.autosize.aspx), there's a note about Label's AutoSize property:

When added to a form using the designer, the default value is true. When instantiated from code, the default value is false.

The question is: how can I override a Label control and set its AutoSize property's design-time default value to false?

(Update)

And this doesn't work:

class MyLabel : Label
{
    const bool defaultAutoSize = false;

    public MyLabel()
    {
        AutoSize = defaultAutoSize;
    }

    [DefaultValue(defaultAutoSize)]
    public override bool AutoSize
    {
        get
        {
            return base.AutoSize;
        }
        set
        {
            base.AutoSize = value;
        }
    }
}
like image 555
EFanZh Avatar asked Mar 16 '12 03:03

EFanZh


2 Answers

Simply use inheritance. You will have to use your custom Label instead of the System one, though.

public class MyLabel:Label
{
    public MyLabel():base()
    {
        base.AutoSize = false;
    }
}

You can put this directly into your code and modify the code like below. Or you can put this class into its own library, which you should then be able to load into the toolbox and use like any other component.

For this to work from the toolbox, it seems that you need to override the InitLayout, like below, and add an attribute to the AutoSize property so it is not serialized into the designer:

    [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
    [DefaultValue(false)]
    public override bool AutoSize
    {
        get
        {
            return base.AutoSize;
        }
        set
        {
            base.AutoSize = value;
        }
    }

    protected override void InitLayout()
    {
        base.InitLayout();
        base.AutoSize = false;
    }

If you are not using the toolbox, then once you drop your normal label onto your form, you need to go into the [Form].Designer.cs and find and modify your labels:

this.label1 = new MyLabel();// new System.Windows.Forms.Label();

//this.label1.AutoSize = true;

You have to remove the preset AutoSize property because when you drop the label it sets it in the designer, and even if you change the label instantiation to be your type, the manual AutoSize set will override your default

like image 164
Justin Pihony Avatar answered Sep 19 '22 18:09

Justin Pihony


The Label control has an attribute:

[ToolboxItem("System.Windows.Forms.Design.AutoSizeToolboxItem,System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]

which cause the strange AutoSize problem.

I can disable it by this:

[ToolboxItem(true)]
class MyLabel : Label
{
}
like image 20
EFanZh Avatar answered Sep 21 '22 18:09

EFanZh