如何使两个文本框能够双向通信?

3

我正在制作一个简单的WinForms 单位转换器,这意味着我需要两个文本框,在文本框1中输入“来自”值,在文本框2中输出转换后的值。我还希望实现另一种方式,即从文本框2中获取输入,并将转换后的值打印在文本框1中。我该如何做到这一点?


你尝试过使用TextChanged事件了吗? - Bagus Tesa
1
@BagusTesa 在两个文本框上使用 TextChanged 事件来修改另一个文本框的内容会递归和无限地触发事件。在进行更改之前,您可能需要分离事件。 - Cid
@Cid,你可以在TextBox1.TextChanged事件的开始处修改时取消注册TextBox2上的事件,然后在结束时重新注册它。或者使用KeyPressed事件。 - Antoine
也许 leave 事件是您要寻找的。或者您想要为非多行文本框在按下回车键时进行验证 https://dev59.com/73A65IYBdhLWcg3w7DT8 - xdtTransform
我建议使用Validated事件,在第一个文本框失去焦点时更新另一个文本框。 - Mong Zhu
现在编写转换逻辑。包括单位等,将其封装在一个带有充分参数的良好函数中。在Visual Studio中,选择一个TB,在右侧的属性窗口中选择事件栏。双击您想要的每个事件。复制并粘贴方法调用。对于其他TB也做同样的操作。 - xdtTransform
2个回答

5
你需要为 TextBox两个 控件实现 TextChanged 事件处理程序;唯一的困难在于了解哪个控件(textBox1 还是 textBox2)被用户更改(以防止当 textBox1 的值转换为 textBox2,而后者又转换为 textBox1 等等时出现无限循环)。你可以通过检查 Focused 来实现。
private void textBox1_TextChanged(object sender, EventArgs e) {
  // Do nothing, if user is changing some other control (e.g. textBox2)
  if (!(sender as Control).Focused)
    return;

  // Having textBox1.Text value convert it forward to textBox2.Text
  textBox2.Text = Convert(textBox1.Text); 
}

private void textBox2_TextChanged(object sender, EventArgs e) {
  // Do nothing, if user is changing some other control (e.g. textBox1)
  if (!(sender as Control).Focused)
    return;

  // Having textBox2.Text value convert it backward to textBox1.Text
  textBox1.Text = ReverseConvert(textBox2.Text); 
}

或者使用 事件处理程序 进行操作(这更加 灵活,特别是如果您可以通过按钮单击开始转换,这样既不需要将焦点放在textBox1也不需要放在textBox2上):

private void textBox1_TextChanged(object sender, EventArgs e) {
  textBox2.TextChange -= textBox2_TextChanged;

  try {
    // Since textBox2.TextChanged switched off,
    // changing textBox2.Text will not cause textBox1.Text change
    textBox2.Text = Convert(textBox1.Text); 
  }
  finally {
    textBox2.TextChange += textBox2_TextChanged;
  }
}

private void textBox2_TextChanged(object sender, EventArgs e) {
  textBox1.TextChange -= textBox1_TextChanged;

  try {
    // Since textBox1.TextChanged switched off,
    // changing textBox1.Text will not cause textBox2.Text change
    textBox1.Text = ReverseConvert(textBox2.Text); 
  }
  finally {
    textBox1.TextChange += textBox1_TextChanged;
  }
}

0

您可以在一个事件处理程序中处理两个文本框的文本更改事件(它将触发两次事件)

private void textBox_TextChanged(object sender, EventArgs e)
{
    if (((TextBox)sender).Equals(textBox1)) 
        textBox2.Text = Convert((TextBox)sender).Text);
    else
        textBox1.Text = ReverseConvert((TextBox)sender).Text);
}

2
如果我修改 textBox1.Text,那么 textBox2.Text 将会被改变,从而导致 textBox1.Text 的修改;如果我们有 (单位转换) 舍入误差,那么 textBox1.Text 将再次被转换,我们可能会遇到一个无限循环 - Dmitry Bychenko
如果转换是可逆的,那么就不会有问题。 - Reza Aghaei
@Reza Aghaei:如果涉及到double类型的值,例如TextBox1: 18.0 -> TextBox2: 15.9999999999 -> TextBox1: 17.9999999999 -> TextBox2: 15.9999999998 -> TextBox1: 17.9999999996 -> ...,这可能会成为一个问题。它可能会停止,循环并不一定是无限的,但是值将被破坏(我想要我的初始值18.0,而不是17.99999994)。 - Dmitry Bychenko
我明白了,在这种情况下,它意味着它是不可逆的,或者正如你所提到的,它会受到舍入问题的影响。 - Reza Aghaei

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接