使用XamlReader.Parse创建的控件不会继承样式

时间:2014-07-23 17:18:33

标签: wpf xaml c#-4.0 xamlreader

在我的应用程序中,用户可以键入HTML,然后将其转换为XAML。然后我使用XamlReader.Parse方法解析XAML并将其添加到FlowDocument

例如,假设我有一个存储在字符串中的段落的XAML,然后我解析它并将其添加到FlowDocument,如下所示:

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);

请注意,该段落已指定样式。该样式在FlowDocument的资源中定义。

<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>

你可以看到我定义了两种风格。第一个是隐式样式,第二个是使用BasedOn属性扩展第一个样式。当我动态地将Paragraph添加到FlowDocument时,它确实会选择“大”样式。但是,有一点需要注意,它没有采用隐式样式的Red Foreground颜色。我怎样才能让它同时接收?

当我解析XAML时,这似乎只是一个问题。如果我只是实例化一个新的Paragraph对象并将其添加到FlowDocument,它确实会选择这两种样式。

0 个答案:

没有答案