导航

WinForms中的Label的AutoSize属性

Posted on 2014-08-26 17:52  胡不归  阅读(1083)  评论(0编辑  收藏  举报

当大量使用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;
    }
}