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

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

提交回复
热议问题