繁体   English   中英

(C#WPF)如何更改textrange背景颜色?

[英](C# WPF) How to change textrange background color?

我正在使用“ flowdocumentreader”显示文本,“ flowdocumentreader”的xaml代码很简单:

<FlowDocumentReader x:Name="myDocumentReader" ViewingMode="Scroll" VerticalAlignment="Stretch" ContextMenuOpening="myDocumentReader_ContextMenuOpening" Margin="0,0,0,0" Grid.Row="1" PreviewMouseDown="myDocumentReader_PreviewMouseDown">
    <FlowDocument x:Name="flow" LineHeight="{Binding ElementName=slider2, Path=Value}" PagePadding="{Binding ElementName=slider, Path=Value}">
        <Paragraph x:Name="paraBodyText"/>
    </FlowDocument>
</FlowDocumentReader>

我将.rtf文档加载到“ flowdocumentreader”中,如下所示:

paraBodyText.Inlines.Clear();
string temp = File.ReadAllText(dlg.FileName, Encoding.UTF8);
MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(temp));
TextRange textRange = new TextRange(flow.ContentStart, flow.ContentEnd);
textRange.Load(stream, DataFormats.Rtf);
myDocumentReader.Document = flow;

现在,我的问题是,如何在“ flowdocumentreader”中获取字符串的背景色?

我知道如何搜索字符串,但不知道如何检查此类字符串的背景色。 有没有办法做到这一点? 我试图获取字符串的文本范围,然后执行以下操作:

TextRange selection = ....; // this is the textrange of the string
var a = selection.GetPropertyValue(TextElement.BackgroundProperty)

但是,变量“ a”始终返回null。 :(

在此先感谢您的时间。

编辑 :我加载到“ FlowDocumentReader”中的.rtf文档具有背景色。 有些是绿色的,有些是黄色的。

在此处输入图片说明

但是,变量“ a”始终返回null。 :(

如果您实际上设置了背景色怎么办?:

TextRange selection = new TextRange(flow.ContentStart, flow.ContentEnd);
var a = selection.GetPropertyValue(TextElement.BackgroundProperty);
selection.ApplyPropertyValue(TextElement.BackgroundProperty, Brushes.Yellow);
a = selection.GetPropertyValue(TextElement.BackgroundProperty);

<FlowDocumentReader x:Name="myDocumentReader" ViewingMode="Scroll" VerticalAlignment="Stretch">
    <FlowDocument x:Name="flow">
        <Paragraph x:Name="paraBodyText">
            some text...
        </Paragraph>
    </FlowDocument>
</FlowDocumentReader>

TextRange的TextElement.BackgroundProperty属性没有默认值,这就是为什么您使用上述示例代码第一次从GetPropertyValue方法获得空引用的原因。

已经有一段时间了,但是最终发现了为什么,问题是有时将Background属性添加到包含文本Run的Span中,而我们要求的是Run背景色,而不是其父级(Span或Paragraph),我的问题/答案中的更多信息:

C#WPF RichText Box BackgroundProperty从文件读取时返回null

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM