自定义控件动态大小c#



我有一个UserControl上有一个文本框。我不想根据字体大小来改变控件的大小,这样它就不会切断文本的底部,但是我对控件大小所做的更改根本不起作用。

public override Font Font
{
    get
    {
        return base.Font;
    }
    set
    {
        textBox1.Font = base.Font = value;
        if (Font.Height != this.Height)
            this.Height = Font.Height;
    }
}
protected override void OnResize(EventArgs e)
{
    textBox1.Size = new Size(this.Width - (_textboxMargin * 2 + _borderWidth * 2), this.Height - (_textboxMargin * 2 + _borderWidth * 2));
    textBox1.Location = new Point(_textboxMargin, _textboxMargin);
    base.OnResize(e);
}

当OnResize事件在属性设置后被触发时,这。高度保持原值

——编辑——

原来的问题是,我设置字体之前的控制大小,所以它被覆盖。但这发生在我使用这个控件的页面的设计器中。我怎样才能避免这种情况再次发生呢?

因此,为了解决这个覆盖问题,我做了以下操作:

public override Font Font
{
    get
    {
        return base.Font;
    }
    set
    {
        textBox1.Font = base.Font = value;
        if (Font.Height != this.Height)
        {
            this.Height = Font.Height;
            textBox1.Size = new Size(this.Width - (_textboxMargin * 2 + _borderWidth * 2), this.Height - (_textboxMargin * 2 + _borderWidth * 2));
            textBox1.Location = new Point(_textboxMargin, _textboxMargin);
        }
    }
}
protected override void OnResize(EventArgs e)
{
    if (this.Height < Font.Height)
        this.Height = Font.Height;
    base.OnResize(e);
}

最新更新