我怎样才能代替'& # 39;用" "

本文关键字:quot | 更新日期: 2023-09-27 18:07:46

我试图在VS 2010的WPF富文本框中将' '替换为藏文' '。

假设我有一个富文本框,文本如下:

སྐད བརྡའི སྒྲིག རིམ སྐྲུན པའི་

以下是我期望通过使用WPF richTextBox得到的输出。

སྐད་བརྡའི་སྒྲིག་རིམ་སྐྲུན་པའི་

我有语言键盘:

Monlam Bod-yig3.01 Unicode

我怎样才能代替'& # 39;用" "

请参考此链接:自动替换wpf richtextbox中的文本


由于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");
    }

这里的用户试图用个人电脑代替pc,您可以通过将"'"替换为""来模拟相同的行为。

如果这不能满足您的需要,您可以尝试以下步骤:

  1. 为RichTextBox引发一个TextChangedEvent

  2. 检查文本是否为' ',从eventargs

  3. 如果为真,从RichTextBox中删除一个字符。文本并添加"

编辑:请参阅select语句(尽管这是一个粗糙的方法,并且只有当您在选择后输入时才会有用)

string _Text = new TextRange(richTextBox1.Document.ContentStart, richTextBox1.Document.ContentEnd).Text;
_Text = _Text.Replace(" ", "“་”ཚེག"); // 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
}
richTextBox1.Selection.Select(_Text.Length-1, _Text.Length);