2012-09-27 69 views
0

我是devexpress WPF應用程序中的新用戶。我真的想學習如何檢測文本框事件的任何變化?例如;有2個文本框(devexpress)(txt1,txt2)。如果我刪除txt1上的值,txt2必須刪除自己的值。如何處理Devexpress WPF文本框更改事件?

這樣的:

private void txt1_KeyDown(object sender, KeyEventArgs e) 
    { 
     if (e.Key == Key.Delete) 
     { 
      txt2.Text = String.Empty; 
     } 
    } 

是真的嗎?你可以幫我嗎?

+0

看看這個SO帖子:http://stackoverflow.com/questions/7271101/wpf-textbox-textchanged-event-on-programmatic-vs-user-change-of-text-contents –

回答

1

如果TXT2的文本必須是完全一樣的像txt1中,使用時綁定:

<TextBox Name="txt2" Text="{Binding ElementName=txt1, Path=Text}"/> 

如果你只是想改變,嘗試這種(使用框TextChanged-事件代替的KeyDown,因爲你也可以粘貼到字符串文本框):

string oldtext = ""; 
private void TextBox_TextChanged(object sender, TextChangedEventArgs e) 
{ 
    string removedstring = ""; 
    string addedstring = ""; 
    TextBox source = (TextBox)e.Source; 
    TextChange t = e.Changes.First(); 

    if (t.RemovedLength > 0) 
    { 
     removedstring = oldtext.Substring(t.Offset, t.RemovedLength); 
    } 

    if (t.AddedLength > 0) 
    { 
     addedstring = source.Text.Substring(t.Offset, t.AddedLength); 
    } 

    oldtext = source.Text; 
} 

如果你想通過代碼來設置txt2.Text = txt1.Text

private void TextBox_TextChanged(object sender, TextChangedEventArgs e) 
    { 
     TextBox source = (TextBox)e.Source; 
     TextChange t = e.Changes.First(); 

     string first = txt2.Text.Substring(0, t.Offset); 
     string added = source.Text.Substring(t.Offset, t.AddedLength); 
     string last = (t.Offset+1>tbrt.Text.Length)?"":txt2.Text.Substring(t.Offset, txt2.Text.Length-1); 
     last = last.Remove(0, t.RemovedLength); 
     txt2.Text = first + added + last; 
    }