的TextRange和RichTextBox的在C#WPF(TextRange and RichTe

2019-10-17 01:03发布

我一直在试图写一个程序来搜索一个RichTextBox一个字。 我做了大部分,但它看起来像我错过了一些东西。 我要的颜色找到的话让我写了以下内容:

private void button1_Click(object sender, RoutedEventArgs e)
    {
        richTextBox1.SelectAll();
        string words = richTextBox1.Selection.Text; // to get the the whole text

        int length = words.Length;                  // length of text

        string search = textBox1.Text;              // the word being searched for
        int search_length = search.Length;


        int index =0;                               // to go through the text
        int endIndex = 0;                           // the end of the got word

         // pointer to the begining and the ending of the word which will be colored.
        TextPointer start_pointer, end_pointer;   

        if(length>0 &&search_length>0)              // text exists
        while(index<length-search_length)  
        {
            index = words.IndexOf(search, index);
            if (index < 0) // not found
                break;
             endIndex = index+search.Length-1;       // last char in the word
             start_pointer = richTextBox1.Document.ContentStart.GetNextInsertionPosition(LogicalDirection.Forward).GetPositionAtOffset(index, LogicalDirection.Forward);
             end_pointer = richTextBox1.Document.ContentStart.GetNextInsertionPosition(LogicalDirection.Forward).GetPositionAtOffset(endIndex + 1, LogicalDirection.Forward);

            TextRange got = new TextRange(start_pointer, end_pointer);

 //just for debugging
            MessageBox.Show("start =" + index + " end =" + endIndex + " " + got.Text);

            got.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.Blue));
            index =endIndex+1;
        }

第一个字是彩色的。 但接下来的话不是(即如果文字是“去上学,我会去市场”,字“走”是搜索,我按下搜索按钮,结果将被着色的第一个“走出去”,但第二个将不着色)。

我估计,这是因为TextRange的工作不正常,或在TextPointer事情错了。 此外,指数和endIndex是正确的 - 我已经测试过他们。

我感谢您的帮助。

Answer 1:

试试这个代码:

 TextRange rangeText = new TextRange(richTextBox.Document.ContentEnd, richTextBox.Document.ContentEnd);
 rangeText.Text = "Text1 ";
 rangeText.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Blue);
 rangeText.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);

 TextRange rangeWord = new TextRange(richTextBox.Document.ContentEnd,        richTextBox.Document.ContentEnd);
 rangeWord.Text = "word ";
 rangeWord.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Red);
 rangeWord.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Regular);

 TextRange rangeTextOne = new TextRange(richTextBox.Document.ContentEnd,     richTextBox.Document.ContentEnd);
 rangeTextOne.Text = "Text2 ";
 rangeTextOne.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Blue);
 rangeTextOne.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);


文章来源: TextRange and RichTextBox in C# WPF