[英]How can I change the selected text background color in Rich text box wpf c#
如何在RichTextBox
控件中顯示html文本?
實際上我想在C#wpf中更改RichTextBox
中的選定文本背景顏色。 我嘗試了這段代碼,但它沒有顯示格式化文本。
請幫幫我...提前致謝!
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())));
}
}
}
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.