In my application the user can type in HTML, which then gets converted to XAML. I then parse the XAML using the XamlReader.Parse
method and add it to a FlowDocument
.
For example, let's suppose I have the XAML for a paragraph stored in a string, and then I parse it and add it to a FlowDocument
like so:
var xaml = @"<Paragraph Style=""{DynamicResource Big}"" xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"">My paragraph</Paragraph>";
var paragraph = (Paragraph)XamlReader.Parse(xaml);
MyDocument.Blocks.Add(paragraph);
Notice that the paragraph has a Style specified. That Style is defined in the FlowDocument
's Resources.
<RichTextBox>
<FlowDocument x:Name="MyDocument">
<FlowDocument.Resources>
<Style TargetType="{x:Type Paragraph}">
<Setter Property="Foreground"
Value="Red" />
</Style>
<Style TargetType="{x:Type Paragraph}"
BasedOn="{StaticResource {x:Type Paragraph}}"
x:Key="Big">
<Setter Property="FontSize"
Value="24" />
</Style>
</FlowDocument.Resources>
</FlowDocument>
</RichTextBox>
You can see that I've defined two styles. The first is an implicit style, and the second extends the first using the BasedOn
attribute. When I dynamically add the Paragraph
to the FlowDocument
it does pick up the 'Big' Style. However, there's a caveat, it does not pick up the Red Foreground color of the implicit style. How can I make it pick up both?
This only seems to be a problem when I parse the XAML. If I just instantiate a new Paragraph
object and add it to the FlowDocument
, it does indeed pick up both styles.