(C#WPF)如何更改文本范围背景颜色?

时间:2017-01-10 20:46:31

标签: c# wpf background-color flowdocument

我使用“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文档具有背景颜色。有些是绿色的,有些是黄色的。

enter image description here

2 个答案:

答案 0 :(得分:2)

  

但是,变量“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方法返回空引用的原因。

答案 1 :(得分:0)

已经有一段时间但终于要发现原因,问题是有时候Background属性被添加到包含文本Run的Span中,我们要求运行背景颜色,而不是其父颜色(跨度或段落),我的问题/答案中的更多信息:

C# WPF RichText Box BackgroundProperty returns null when reading from file

相关问题