如何找到使用 TextChanged 添加的文本 [英] How do I find what text had been added with TextChanged
问题描述
我希望在文本框中的文本和变量中的字符串之间进行同步.我找到了如何获取更改字符串的索引(在文本框中)、添加的长度和删除的长度,但我如何才能真正找到添加的字符串?
I'm looking to synchronize between a text in the textbox and string in a variable. I found how to get the index in which the string was changed (in the textbox), the length added and length removed, but how can I actually find the string added?
到目前为止,我已经使用了 TextChangedEventArgs.Changes,并获得了其中项目的属性 (ICollection).
So far I've used TextChangedEventArgs.Changes, and got the properties of the items in it (ICollection).
我正在尝试创建一个密码框,我可以在其中通过函数显示实际密码.因此我不希望文本框直接同步(例如,在文本框中会出现*****"和字符串hello").
I'm trying to create a password box in which I could show the actual password by a function. hence I do not want the textbox to synchronize directly (for example, in the textbox would appear "*****" and in the string "hello").
推荐答案
如果你只想添加文本,你可以这样做
If you want only text added you can do this
string AddedText;
private void textbox_TextChanged(object sender, TextChangedEventArgs e)
{
var changes = e.Changes.Last();
if (changes.AddedLength > 0)
{
AddedText = textbox.Text.Substring(changes.Offset,changes.AddedLength);
}
}
编辑
如果您想添加和删除所有文本,您可以这样做
If you want all added and remove text you can do this
string oldText;
private void textbox_GotFocus(object sender, RoutedEventArgs e)
{
oldText = textbox.Text;
}
string AddedText;
string RemovedText;
private void textbox_TextChanged(object sender, TextChangedEventArgs e)
{
var changes = e.Changes.Last();
if (changes.AddedLength > 0)
{
AddedText = textbox.Text.Substring(changes.Offset, changes.AddedLength);
if (changes.RemovedLength == 0)
{
oldText = textbox.Text;
RemovedText = "";
}
}
if (changes.RemovedLength > 0)
{
RemovedText = oldText.Substring(changes.Offset, changes.RemovedLength);
oldText = textbox.Text;
if (changes.AddedLength == 0)
{
AddedText = "";
}
}
}
这篇关于如何找到使用 TextChanged 添加的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!