自动替换wpf RichTextBox中的文本

2024-03-15

我有一个 WPF .NET 4 C#RichTextBox我想用其他字符替换该文本框中的某些字符,这将发生在KeyUp event.

我想要实现的目标是将首字母缩略词替换为完整单词,例如:
pc=个人电脑
sc=星际争霸
etc...

我查看了一些类似的线程,但我发现的任何内容在我的场景中都没有成功。

最终,我希望能够通过首字母缩略词列表来做到这一点。但是,我什至在替换单个缩写词时都遇到问题,有人可以帮忙吗?


Because System.Windows.Controls.RichTextBox没有财产Text要检测其值,您可以使用以下方法检测其值

string _Text = new TextRange(richTextBox1.Document.ContentStart, richTextBox1.Document.ContentEnd).Text;

那么,你可以改变_Text并使用以下命令发布新字符串

_Text = _Text.Replace("pc", "Personal Computer");
if (_Text != new TextRange(richTextBox1.Document.ContentStart, richTextBox1.Document.ContentEnd).Text)
{
new TextRange(richTextBox1.Document.ContentStart, richTextBox1.Document.ContentEnd).Text = _Text;
}

所以,它看起来像这样

string _Text = new TextRange(richTextBox1.Document.ContentStart, richTextBox1.Document.ContentEnd).Text;
_Text = _Text.Replace("pc", "Personal Computer"); // Replace pc with Personal Computer
if (_Text != new TextRange(richTextBox1.Document.ContentStart, richTextBox1.Document.ContentEnd).Text)
{
new TextRange(richTextBox1.Document.ContentStart, richTextBox1.Document.ContentEnd).Text = _Text; // Change the current text to _Text
}

Remark: 而不是使用Text.Replace("pc", "Personal Computer");你可以声明一个List<String>您可以在其中保存字符及其替换内容

Example:

    List<string> _List = new List<string>();
    private void richTextBox1_TextChanged(object sender, TextChangedEventArgs e)
    {

        string _Text = new TextRange(richTextBox1.Document.ContentStart, richTextBox1.Document.ContentEnd).Text;
        for (int count = 0; count < _List.Count; count++)
        {
            string[] _Split = _List[count].Split(','); //Separate each string in _List[count] based on its index
            _Text = _Text.Replace(_Split[0], _Split[1]); //Replace the first index with the second index
        }
        if (_Text != new TextRange(richTextBox1.Document.ContentStart, richTextBox1.Document.ContentEnd).Text)
        {
        new TextRange(richTextBox1.Document.ContentStart, richTextBox1.Document.ContentEnd).Text = _Text;
        }
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        // The comma will be used to separate multiple items
        _List.Add("pc,Personal Computer");
        _List.Add("sc,Star Craft");

    }

Thanks,
我希望你觉得这有帮助 :)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

自动替换wpf RichTextBox中的文本 的相关文章

随机推荐