[英]How can I sync two TextBox control's Text properties?
If I have two text boxes on a form, how can I make it so that their text properties are perfectly synced? 如果我在表单上有两个文本框,如何使它们的文本属性完美同步? Similar to what would happen if they both processed the same KeyDown event.
如果它们都处理相同的KeyDown事件,将会发生类似的情况。
I would do it this way: 我会这样:
textBox1.TextChanged += (s, _) =>
{
if (!textBox2.Focused && textBox1.Text != textBox2.Text)
{
textBox2.Text = textBox1.Text;
}
};
textBox2.TextChanged += (s, _) =>
{
if (!textBox1.Focused && textBox2.Text != textBox1.Text)
{
textBox1.Text = textBox2.Text;
}
};
Basically I'm responding to the TextChanged
even on each text box, but making sure that the target text box doesn't have focus and that the text actually has changed. 基本上,我什至在每个文本框上都对
TextChanged
做出响应,但要确保目标文本框没有焦点并且文本实际上已更改。 This prevents infinite back-and-forth loop trying to update the text and it makes sure that the current insertion point isn't changed by the text being overwritten. 这样可以防止无限次来回循环尝试更新文本,并且可以确保当前的插入点不会因被覆盖的文本而改变。
I would say that you partially answered your own question, have them both assigned to the same TextChanged
EventHandler check which textbox has changed then update the Text property of the other one, something like this. 我想说,您部分回答了自己的问题,将它们都分配给同一个
TextChanged
EventHandler,检查哪个文本框已更改,然后更新另一个文本框的Text属性,类似这样。
private void textBox_TextChanged(object sender, EventArgs e)
{
if (((TextBox)sender).Equals(textBox1))
textBox2.Text = ((TextBox)sender).Text;
else
textBox1.Text = ((TextBox)sender).Text;
}
Modified Code to Keep Carat Position Synced between the two TextBox's , see if this is what you are wanting. 修改代码以保持克拉位置在两个TextBox之间保持同步,看看这是否是您想要的。
private void textBox_TextChanged(object sender, EventArgs e)
{
TextBox tb = (TextBox)sender;
if (tb.Equals(textBox1))
{
if (textBox2.Text != tb.Text)
{
textBox2.Text = tb.Text;
textBox2.SelectionStart = tb.SelectionStart;
textBox2.Focus();
}
}
else
{
if (textBox1.Text != tb.Text)
{
textBox1.Text = tb.Text;
textBox1.SelectionStart = tb.SelectionStart;
textBox1.Focus();
}
}
}
I would simply do as follows: 我可以简单地做如下:
bool flag1, flag2;
private void t1_TextChanged(object sender, EventArgs e)
{
if (flag2) return;
flag1 = true;
t2.Text = t1.Text;
flag1 = false;
}
private void t2_TextChanged(object sender, EventArgs e)
{
if (flag1) return;
flag2 = true;
t1.Text = t2.Text;
flag2 = false;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.