c# - 如何更改富文本框 wpf c# 中选定文本的背景颜色#

标签 c# wpf

如何在 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);

关于c# - 如何更改富文本框 wpf c# 中选定文本的背景颜色#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18015380/

相关文章:

c# - 如何修复文件格式和扩展名不匹配?

C# 在 Main() 中等待所有线程完成

c# - 文本框样式正在为所有文本框设置

c# - 嵌入式wpf文本框不接受输入

wpf - 在 ResourceDictionary 中定义 UserControl?

c# - 在 MVVM 中放置全局变量的位置(Caliburn micro)

c# - DynamicLINQ - 在字符串内转义双引号

c# - 如何从集成测试将文件上传到端点

c# - 为透明的点击覆盖寻找一个好的 WPF 解决方案

具有参数化构造函数的 Wpf 用户控件