c# - 自动替换wpf richtextbox中的文本

标签 c# wpf .net-4.0 richtextbox

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

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

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

最终,我希望能够使用首字母缩略词列表来完成此操作。但是,我什至连替换单个首字母缩略词都遇到了问题,有人可以帮忙吗?

最佳答案

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

    }

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

关于c# - 自动替换wpf richtextbox中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13041350/

相关文章:

c# - 解释 C# 堆栈跟踪

c# - 在Visual Studio 7.5 Mac中找不到指定的框架 'Microsoft.AspNetCore.App'和版本 '2.1.0' docker

c# - 如何在 WPF 中的 Popup 控件顶部获取消息框?

c# - 删除多元素string []数组中的重复项?

c# - 如何使用 configurationManager 从 .Net 4.0 中的 App.config 读取值?

c# - ServiceStack V3 与 V4

c# - 如何更改 ASP.NET Core 中资源文件的命名空间?

wpf - 如何在 WPF DataGrid 中的连续单元格之间强制零像素间隙

c# - 如何创建 WPF 响应式菜单栏(全角)

.net - .NET 4.0 是否存在 mdbg 托管调试器示例?