确定何时以及在文本框中添加或删除哪个字符

Determine when and which character is added or deleted in a Text Box(确定何时以及在文本框中添加或删除哪个字符)
本文介绍了确定何时以及在文本框中添加或删除哪个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 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. :)

还是谢谢.

这篇关于确定何时以及在文本框中添加或删除哪个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)