自动替换wpf richtextbox中的文本

时间:2012-10-24 00:32:19

标签: c# wpf .net-4.0 richtextbox

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

我想要实现的是用完整的单词替换首字母缩略词,例如:
pc =个人电脑
sc = starcraft
等...

我看了几个类似的主题,但我发现的任何内容在我的场景中都没有成功。

最终,我希望能够通过一系列首字母缩略词来做到这一点。但是,即使更换单个首字母缩略词,我也有问题,任何人都可以帮忙吗?

1 个答案:

答案 0 :(得分: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");

    }

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