问题描述
我正在使用"flowdocumentreader"显示文本,"flowdocumentreader"的xaml代码很简单:
I am using a "flowdocumentreader" to show text, the xaml code of the "flowdocumentreader" is simple:
<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"中,如下所示:
And I load .rtf documents to the "flowdocumentreader" like this:
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"中获取字符串的背景色?
Now, my question is, how to get the background color of a string in the "flowdocumentreader"?
我知道如何搜索字符串,但不知道如何检查此类字符串的背景色.有没有办法做到这一点?我试图获取字符串的文本范围,然后执行以下操作:
I know how to search for a string, but I don't know how to check the back ground color of such string. Is there a way to do that? I tried to get the textrange of the string and then do this:
TextRange selection = ....; // this is the textrange of the string
var a = selection.GetPropertyValue(TextElement.BackgroundProperty)
但是,变量"a"始终返回null. :(
However, the variable "a" always returns null. :(
提前感谢您的时间.
编辑:我加载到"FlowDocumentReader"中的.rtf文档具有背景色.有些是绿色的,有些是黄色的.
EDIT:The .rtf document that I loaded into the "FlowDocumentReader" has background colors. Some are green and some are yellow.
推荐答案
如果您实际上设置了背景色怎么办?:
What if you actually set a background colour?:
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方法获得空引用的原因.
There is no default value for the TextElement.BackgroundProperty property of a TextRange which is why you get a null reference back from the GetPropertyValue method the first time using the above sample code.
这篇关于(C#WPF)如何更改textrange背景颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!