如果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;
}
看看這個SO帖子:http://stackoverflow.com/questions/7271101/wpf-textbox-textchanged-event-on-programmatic-vs-user-change-of-text-contents –