本文介绍了垂直自动调整文本框控件的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C# 表单中,我有一个四面锚定的面板,内部有一个文本框,锚定在顶部/左侧/右侧.

In a C# form, I have a panel anchored all sides, and inside, a textbox, anchored top/left/right.

当文本被加载到文本框时,我希望它自动垂直扩展,这样我就不需要滚动文本框(最多滚动面板,如果有更多的文本不适合面板).有没有办法用文本框做到这一点?(我不限制使用这个控件,所以如果有另一个符合描述的控件,请随时提及)

When text gets loaded into the textbox, i want it to auto expand itself vertically so that I don't need to scroll the textbox (scroll the panel at most, if there is more text that doesn't fit the panel).is there any way to do this with a textbox? (i'm not constrained to use this control so if there's another control that fits the description, feel free to mention it)

推荐答案

我假设这是一个多行文本框,并且您将允许它垂直增长.这段代码运行良好:

I'll assume this is a multi-line text box and that you'll allow it to grow vertically. This code worked well:

    private void textBox1_TextChanged(object sender, EventArgs e) {
        Size sz = new Size(textBox1.ClientSize.Width, int.MaxValue);
        TextFormatFlags flags = TextFormatFlags.WordBreak;
        int padding = 3;
        int borders = textBox1.Height - textBox1.ClientSize.Height;
        sz = TextRenderer.MeasureText(textBox1.Text, textBox1.Font, sz, flags);
        int h = sz.Height + borders + padding;
        if (textBox1.Top + h > this.ClientSize.Height - 10) {
            h = this.ClientSize.Height - 10 - textBox1.Top;
        }
        textBox1.Height = h;
    }

当文本框为空时,你应该做一些合理的事情,比如设置 MinimumSize 属性.

You ought to do something reasonable when the text box is empty, like setting the MinimumSize property.

这篇关于垂直自动调整文本框控件的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 07:31