2013-08-02 1 views
3

Как отображать html-текст в RichTextBox?Как изменить выделенный цвет фона текста в Rich текстовом поле wpf C#

На самом деле я хочу изменить выделенный цвет фона текста в RichTextBox на C# wpf. Я пробовал этот код, но он не отображает форматированный текст.

Пожалуйста, помогите мне ... Спасибо заранее!

void rtbTextEditor_SelectionChanged(object sender, RoutedEventArgs e) 
{ 
    SelectionText = rtbTextEditor.Selection.Text.Trim(); 
    if (SelectionText != string.Empty) 
    { 
     if (VisualEditor.Document.Body != null) 
     { 
      //VisualEditor is web browser 
      VisualEditor.Document.Body.InnerHtml = @"""<html><body><FONT style=""BACKGROUND-COLOR: #ffff00""><bold>""" + rtbTextEditor.Selection.Text + @"""</Bold></FONT></body></html>"""; 
      VisualEditor.Document.ExecCommand("SelectAll", false, null); 
      rtbTextEditor.Document.Blocks.Add(new Paragraph(new Run(VisualEditor.Document.Body.InnerText.ToString()))); 
     } 
    } 
} 
+0

Вы проверили 'SelectionBrush' свойство' RichTextBox'? – Nitesh

ответ

2
private static TextPointer GetTextPointAt(TextPointer from, int pos) 
    { 
    TextPointer ret = from; 
    int i = 0; 

    while ((i < pos) && (ret != null)) 
    { 
     if ((ret.GetPointerContext(LogicalDirection.Backward) == TextPointerContext.Text) || (ret.GetPointerContext(LogicalDirection.Backward) == TextPointerContext.None)) 
      i++; 

     if (ret.GetPositionAtOffset(1, LogicalDirection.Forward) == null) 
      return ret; 

     ret = ret.GetPositionAtOffset(1, LogicalDirection.Forward); 
    } 

    return ret; 
} 

internal string Select(RichTextBox rtb, int offset, int length, Color color) 
{ 
    // Get text selection: 
    TextSelection textRange = rtb.Selection; 

    // Get text starting point: 
    TextPointer start = rtb.Document.ContentStart; 

    // Get begin and end requested: 
    TextPointer startPos = GetTextPointAt(start, offset); 
    TextPointer endPos = GetTextPointAt(start, offset + length); 

    // New selection of text: 
    textRange.Select(startPos, endPos); 

    // Apply property to the selection: 
    textRange.ApplyPropertyValue(TextElement.BackgroundProperty, new SolidColorBrush(color)); 

    // Return selection text: 
    return rtb.Selection.Text; 
} 

И затем использовать его таким образом (я от выбора первого символа пятой в RED):

this.Select(this.myRichTextBox, 0, 5, Colors.Red); 
+0

Да! Это работает .... Спасибо много Nitesh .... –

+0

Добро пожаловать, кстати, я Ajay не Nitesh. Примите это как ответ :) –

+0

Извините Ajay ... Спасибо большое :) –

Смежные вопросы