WPF RichTextBox中的文本自动替换

5
我有一个 WPF .NET 4 C# 的 RichTextBox,想要在文本框中用其他字符替换某些字符,这需要在 KeyUp 事件中发生。
我想要实现的是将缩写替换为全称,例如:
pc = 个人计算机
sc = 星际争霸
等等...
我查看了一些类似的线程,但是我找到的任何内容都不能成功解决我的情况。
最终,我希望能够使用缩写列表来完成此操作。然而,我在替换单个缩写时遇到了问题,有人能帮忙吗?
1个回答

2

由于 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
}

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

示例:

    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");

    }

谢谢,
希望这对您有所帮助 :)


@Mike 没问题,很高兴能帮上忙 :) - Picrofo Software
我发现这行代码 new TextRange(richTextBox1.Document.ContentStart, richTextBox1.Document.ContentEnd).Text = _Text 真的很奇怪。这真的会改变 RichTextBox 中的文本吗? - JobaDiniz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接