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

后端 未结 2 815
温柔的废话
温柔的废话 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: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.

提交回复
热议问题