如何更改富文本框wpf c#中选定的文本背景颜色
本文关键字:文本 背景 颜色 何更改 wpf | 更新日期: 2023-09-27 18:25:53
如何在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;
}
然后以这种方式使用它(我从红色的第一个字符到第五个字符进行选择):
this.Select(this.myRichTextBox, 0, 5, Colors.Red);