简体   繁体   English

Winforms:FlowLayoutPanel中的动态TextBox宽度

[英]Winforms: Dynamic TextBox width in FlowLayoutPanel

I have a Winforms FlowLayoutPanel with several textboxes. 我有一个带有几个文本框的Winforms FlowLayoutPanel。 Is it possible that the textboxes can change their width dynamically dependent on the input of the user, so that the whole input is always displayed for each textbox? 文本框是否可以根据用户的输入动态更改其宽度,以便始终为每个文本框显示整个输入?

You can use the TextChanged event for your TextBoxes to measure the text and set the width of the control. 您可以将TextChanged事件用于TextBoxes来测量文本并设置控件的宽度。 I added a minimum width of 32 in this example to make it practical to the end user: 在此示例中,我添加了最小宽度32,以使其对最终用户实用:

public Form1() {
  InitializeComponent();

  textBox1.MinimumSize = new Size(32, 0);
  textBox2.MinimumSize = new Size(32, 0);
  textBox3.MinimumSize = new Size(32, 0);

  textBox1.TextChanged += textBox_TextChanged;
  textBox2.TextChanged += textBox_TextChanged;
  textBox3.TextChanged += textBox_TextChanged;
}

void textBox_TextChanged(object sender, EventArgs e) {
  TextBox tb = sender as TextBox;
  if (tb != null) {
    tb.Width = TextRenderer.MeasureText(tb.Text, tb.Font, Size.Empty, 
                            TextFormatFlags.TextBoxControl).Width + 8;
  }
}

There is an obvious limitation that the width of the TextBox shouldn't be wider than the FlowLayoutPanel's client width, so you would have to account for that. 有一个明显的限制,即TextBox的宽度不应比FlowLayoutPanel的客户端宽度宽,因此您必须考虑到这一点。 The + 8 for the width is just a fudge number to account for the extra spacing of padding and borders, etc. 宽度的+ 8只是一个软糖数字,用于说明填充和边框等的额外间距。

in case of the textbox get's wider then the FlowLayoutPanel's just set to true the 如果文本框变宽,则FlowLayoutPanel设置为true

TextBox.MultiLine to true don't forget to check the height from the textboxes comparing to the layoutpanel as well 将TextBox.MultiLine设置为true ,别忘了检查文本框与layoutpanel的高度

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM