TargetType上的WPF样式选择器指定嵌套目标类型

Lou*_*ers 3 css wpf xaml css-selectors

我如何指定,例如FlowDocument中表内的所有段落标记(不包括表外的那些).我期待这样的事情:

<Style TargetType="Table">
    <Style TargetType="Paragraph">
        <Setter Property="Margin" Value="0" />
    <Style>
</Style>
Run Code Online (Sandbox Code Playgroud)

但是不允许嵌套样式.

我希望在CSS中实现的等价物如下:

Table Paragraph {margin:0}
Run Code Online (Sandbox Code Playgroud)

因此,表格范围内的所有段落标记的边距都为0.这在WPF中是否可行(在XAML标记部分中)?复杂的WPF样式选择器上的任何好的来源也将不胜感激.

我可以编写代码来完成它,但这不是我想要的.

小智 10

实际上可以通过创建样式然后在Style.Resources属性中包含一个或多个样式来执行类似于CSS的样式嵌套,如下所示:

    <Style TargetType="Table">
        <Style.Resources>
            <Style TargetType="Paragraph">
                <Setter Property="Padding" Value="0" />
            </Style>
        </Style.Resources>
    </Style>
Run Code Online (Sandbox Code Playgroud)

此样式将应用于范围内的所有表,嵌套的段落样式将应用于这些表内的所有段落,但不应用于表外的段落.这是因为将内容放在Resources属性中基本上将它们注入到所有子对象的可见范围内.

你也可以在技术上做这样的多层嵌套来为只在Paragraphs里面的Hyperlinks green上色,这只是在Tables里面:

    <Style TargetType="Table">
        <Style.Resources>
            <Style TargetType="Paragraph">
                <Setter Property="Padding" Value="0" />
                <Style.Resources>
                    <Style TargetType="Hyperlink">
                        <Setter Property="Foreground" Value="Green" />
                    </Style>
                </Style.Resources>
            </Style>
        </Style.Resources>
    </Style>
Run Code Online (Sandbox Code Playgroud)

  • 这是一个更好的答案. (2认同)