问题
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>
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;
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)
However, the variable "a" always returns null. :(
Thanks in advance for your time.
EDIT: The .rtf document that I loaded into the "FlowDocumentReader" has background colors. Some are green and some are yellow.
回答1:
However, the variable "a" always returns null. :(
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>
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.
回答2:
It's been a while but finally got to discover why, the issue is that sometimes the Background property gets added to a Span that contains the text Run and we are asking for the Run background color, not its parent (the Span or the Paragraph), more information in my Question/Answer:
C# WPF RichText Box BackgroundProperty returns null when reading from file
来源:https://stackoverflow.com/questions/41578080/c-wpf-how-to-change-textrange-background-color