You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WPF中如何动态修改Paragraph的背景属性?

WPF RichTextBox Paragraph 动态修改背景问题
  • 创建Paragraph实例时可正常设置Background属性并添加至richTextBox.Document.Blocks:
var p = new Paragraph
{
    LineHeight = 1.8,
    Background = _bgHighlight
};

var m = new Run("test string");
p.Inlines.Add(m);

richTextBox.Document.Blocks.Add(p);
  • 将Paragraph插入Blocks后,直接修改其Background属性无效,尝试的代码如下:
internal static readonly SolidColorBrush _bgHighlight = new SolidColorBrush(Colors.DodgerBlue) { Opacity = .4 };

private static readonly LinearGradientBrush _bgNormalManual = new LinearGradientBrush(Colors.Wheat, Colors.Coral, new Point(0, 0), new Point(0, 1)) { Opacity = .5 };

richTextBox.PreviewMouseLeftButtonDown += (s, e) => {

    Paragraph p = null;
    if (e.OriginalSource is Paragraph x)
    {
        p = x;
    }
    else if (e.OriginalSource is Run y && y.Parent is Paragraph z)
    {
        p = z;
    }
    if (p != null)
    {
        p.Background = _bgNormalManual;
    }
};
  • 尝试通过TextRange修改背景,仅能改变文本内容的背景,无法覆盖整个Paragraph的区域:
var textRange = new TextRange(p.ContentStart, p.ContentEnd);
textRange.ApplyPropertyValue(TextElement.BackgroundProperty, _bgNormal);

内容的提问来源于stack exchange,提问作者long

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 01:37:39