簡體   English   中英

如何同步兩個TextBox控件的Text屬性?

[英]How can I sync two TextBox control's Text properties?

如果我在表單上有兩個文本框,如何使它們的文本屬性完美同步? 如果它們都處理相同的KeyDown事件,將會發生類似的情況。

我會這樣:

        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;
            }
        };

基本上,我什至在每個文本框上都對TextChanged做出響應,但要確保目標文本框沒有焦點並且文本實際上已更改。 這樣可以防止無限次來回循環嘗試更新文本,並且可以確保當前的插入點不會因被覆蓋的文本而改變。

我想說,您部分回答了自己的問題,將它們都分配給同一個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;
}

修改代碼以保持克拉位置在兩個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();
        }
    }
}

我可以簡單地做如下:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM