我在 WPF 应用程序中有一个简单的文本框.
I have a simple text box in a WPF application.
我需要知道何时在文本框中添加/删除了一个字符、哪个字符以及在何处添加或删除了该字符.
I need to know when a character was added/deleted in the text box, which character and where it was added or deleted.
我想过使用TextBox.KeyDown
事件,但是有一些问题:
I thought about using the TextBox.KeyDown
event, but it has some problems:
KeyEventArgs
).有什么想法吗?
找到了解决方案.在 WPF 中,TextBox.TextChanged
事件有一个 TextChangedEventArgs
.在这个类中,有一个名为 Changes
的属性.
Found the solution. In WPF, the TextBox.TextChanged
event has a TextChangedEventArgs
. In this class, there is a property named Changes
.
这是我的代码:
private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
{
foreach (var change in e.Changes)
{
if (change.AddedLength > 0 && change.RemovedLength == 0)
{
if (change.AddedLength == 1)
{
AddCharacter(textBox1.Text[change.Offset], change.Offset);
}
else
{
AddString(textBox1.Text.Substring(change.Offset, change.AddedLength), change.Offset);
}
}
else if (change.AddedLength == 0 && change.RemovedLength > 0)
{
if (change.RemovedLength == 1)
{
RemoveCharacter(change.Offset);
}
else
{
RemoveString(change.Offset, change.RemovedLength + change.Offset);
}
}
else if (change.AddedLength == 1 & change.RemovedLength == 1)
{
ReplaceCharacter(change.Offset, textBox1.Text[change.Offset]);
}
else
{
ReplaceString(change.Offset, change.Offset + change.RemovedLength, textBox1.Text.Substring(change.Offset, change.AddedLength));
}
}
}
现在我只需要等待两天就可以接受这个答案.:)
Now I just need to wait two days to accept this answer. :)
还是谢谢.
这篇关于确定何时以及在文本框中添加或删除哪个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!