[英]C# update two text boxes at the same time?
假设我有两个文本框,一个文本框保存二进制数据,另一个文本框等效于ASCII。 如果用户说更改其中任何一个,那么我如何在不按下按钮的情况下同时更新另一个文本框?
您必须防止无限循环 ( asciiTextBox
更改了binaryTextBox.Text
,而后者更改了asciiTextBox.Text
等),并且您可以实现类似这样的操作:
private void asciiTextBox_TextChanged(object sender, EventArgs e) {
binaryTextBox.TextChanged -= binaryTextBox_TextChanged;
try {
binaryTextBox.Text = BinaryText(asciiTextBox.Text);
}
finally {
binaryTextBox.TextChanged += binaryTextBox_TextChanged;
}
}
private void binaryTextBox_TextChanged(object sender, EventArgs e) {
asciiTextBox.TextChanged -= asciiTextBox_TextChanged;
try {
asciiTextBox.Text = AsciiText(binaryTextBox.Text);
}
finally {
asciiTextBox.TextChanged += asciiTextBox_TextChanged;
}
}
当然,您不需要注销TextChanged
事件并重新注册!
当您使用两个TextBox
控件的TextChanged
事件同步它们的文本时,没有无限循环。 Text
属性检查并且如果新值与以前的值相同,则不会引发TextChanged
事件。
因此,您无需删除处理程序。 只需处理TextChanged
事件并更新其他控件。
在下面的示例中,我有2个TextBox
控件,您都可以键入两个控件,并且反向字符串将显示在另一个TextBox
上:
private void textBox1_TextChanged(object sender, EventArgs e)
{
this.textBox2.Text = new string(this.textBox1.Text.Reverse().ToArray());
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
this.textBox1.Text = new string(this.textBox2.Text.Reverse().ToArray());
}
使用上述模式,您可以简单地使用MakeBinary
和MakeAscci
方法。 您只能使用可逆方法。
您应该使用TextChanged
事件。 当用户在一个文本框中键入内容时,可以在TextChanged
处理程序中进行处理。
为了避免无限循环,您可以在开始时取消订阅TextChange
事件,然后在处理程序结束时再次订阅:
private void TextChangedHandler(object sender, EventArgs e)
{
textbox1.TextChanged -= TextChangedHandler;
textbox2.TextChanged -= TextChangedHandler;
// set textbox values
textbox1.TextChanged += TextChangedHandler;
textbox2.TextChanged += TextChangedHandler;
}
使用TextChanged Event
检查此链接以获取详细信息
码
private void TextBox_TextChanged(object sender, EventArgs e)
{
// update your target text bx over here
}
仅为一个框创建
TextChanged Event
,两个框都将创建无限循环
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.