How to get WinForms custom control's default value to be respected when first dropped on a form

后端 未结 2 812
温柔的废话
温柔的废话 2020-12-17 06:41

I have a class library with a custom control in it:

using System.ComponentModel;
using System.Windows.Forms;

namespace ClassLibrary1
{
    public sealed cla         


        
相关标签:
2条回答
  • 2020-12-17 07:02

    The DefaultValueAttribute has no bearing on it: it mainly controls whether the property value should be serialized or not and whether the value should show in bold in the property editor window.

    If you watch the designer code, initially it gets written out explicitly saving AutoSize as true. Apparently it saved the value because it doesnt match the value specified by the DefaultValue but it is saving the wrong value - apparently the base control hasnt gotten the update yet. Any change causes it to serialize the form again, this time with the correct value.

    I dont know exactly why certain properties dont like being overridden and changed from the constructor, but there are a few that don't immediately take. AutoSize is one that gets handled thru SetStyle calls and/or thru some CommonProperties helper.

    One way to set some of these is to implement ISupportInitialize to set the value after the control has been set from the designer properties. A simpler way is to override OnHandleCreated:

    protected override void OnHandleCreated(EventArgs e)
    {
        base.OnHandleCreated(e);
        base.AutoSize = false;
    }
    

    Seems to work as desired.

    0 讨论(0)
  • 2020-12-17 07:12

    The default values which you assign in constructor are respected in general. But for some cases the default values will be changed using designer, for example by the CreateComponentsCore method of ToolboxItem of the control.

    The default value for AutoSize property for Label is false and you even don't need to override it or set it in constructor. But an AutoSizeToolboxItem has been assigned to Label which sets AutoSize to true when you drop an instance of Label on designer. To remove this behavior, it's enough to assign a new ToolboxItemto your control:

    using System.ComponentModel;
    using System.Drawing.Design;
    using System.Windows.Forms;
    
    namespace ClassLibrary1
    {
        [ToolboxItem(typeof(ToolboxItem))]
        public sealed class CustomLabel : Label
        {
        }
    }
    

    Note 1: Just for your information, the ToolboxItem has a CreateComponentsCore method which you can use it to to some initialization tasks when dropping control on design surface.

    Note 2 I should also add, the CreateComponentCore method will just run when you drop the component from toolbox to design surface. It describes why after dropping it on form, it's auto-size, because it's set by CreateComponentCore after your constructor. But after you open the form again, this time, just your constructor will run and set the property to false.

    0 讨论(0)
提交回复
热议问题