WinForms中的Label的AutoSize属性

当大量使用UserControl组合UI时,如果更改了Label的Text属性,Label.AutoSize属性会影响UserControl的OnLoad事件的发生顺序;

public override string Text
{
    get
    {
        return base.Text;
    }
    set
    {
        base.Text = value;
    }
}

public virtual string Text
{
    get
    {
        if (!this.CacheTextInternal)
        {
            return this.WindowText;
        }
        if (this.text != null)
        {
            return this.text;
        }
        return "";
    }
    set
    {
        if (value == null)
        {
            value = "";
        }
        if (value == this.Text)
        {
            return;
        }
        if (this.CacheTextInternal)
        {
            this.text = value;
        }
        this.WindowText = value;
        this.OnTextChanged(EventArgs.Empty);
        if (this.IsMnemonicsListenerAxSourced)
        {
            for (Control control = this; control != null; control = control.ParentInternal)
            {
                Control.ActiveXImpl activeXImpl = (Control.ActiveXImpl)control.Properties.GetObject(Control.PropActiveXImpl);
                if (activeXImpl != null)
                {
                    activeXImpl.UpdateAccelTable();
                    return;
                }
            }
        }
    }
}

protected override void OnTextChanged(EventArgs e)
{
    using (LayoutTransaction.CreateTransactionIf(this.AutoSize, this.ParentInternal, this, PropertyNames.Text))
    {
        this.MeasureTextCache.InvalidateCache();
        base.OnTextChanged(e);
        this.AdjustSize();
        base.Invalidate();
    }
}

internal void AdjustSize()
{
    if (!this.SelfSizing)
    {
        return;
    }
    if (!this.AutoSize && ((this.Anchor & (AnchorStyles.Left | AnchorStyles.Right)) == (AnchorStyles.Left | AnchorStyles.Right) || (this.Anchor & (AnchorStyles.Top | AnchorStyles.Bottom)) == (AnchorStyles.Top | AnchorStyles.Bottom)))
    {
        return;
    }
    int height = this.requestedHeight;
    int width = this.requestedWidth;
    try
    {
        Size size = this.AutoSize ? base.PreferredSize : new Size(width, height);
        base.Size = size;
    }
    finally
    {
        this.requestedHeight = height;
        this.requestedWidth = width;
    }
}

原文地址:https://www.cnblogs.com/hubo0831/p/3937867.html