直接儿童的样式

问题描述

鉴于此示例 XAML:

<TabControl>
    <TabItem Header="Test">
        <Grid> <!-- outer grid that should receive the styles -->
            <Grid.RowDeFinitions><!-- ... --></Grid.RowDeFinitions>
            <Grid.ColumnDeFinitions><!-- ... --></Grid.ColumnDeFinitions>
            <Grid Grid.Row="1" Grid.Column="1">
                <!-- inner grid,should NOT receive the styles -->
            </Grid>
        </Grid>
    </TabItem>
</TabControl>

如何为 Grid 的所有直接 TabItem 子项设置样式,并且在层次结构中没有其他 Grid 的更深层次?

这是我尝试过的(我把它放在 App.xml 中):

<Style targettype="TabItem">
    <Style.Resources>
        <Style targettype="Grid">
            <Setter Property="Margin" Value="10" />
        </Style>
    </Style.Resources>
</Style>

(我知道我可以使用 Style={StaticResource ...} 分配某些样式,但我必须将它单独应用于所有 Grid,这似乎有很多不必要的代码......)

解决方法

如何为 Grid 的所有直接 TabItem 子项设置样式,并且在层次结构中没有其他 Grid 的更深层次?

通过以一种或另一种方式为所有外部 Style 元素显式设置 Grid 属性。

例如,您可以创建一个自定义 Grid 类型,将 Style 应用于:

public class OuterGrid : Grid { }

XAML

<Style TargetType="local:OuterGrid">
    <Setter Property="Margin" Value="10" />
</Style>
...
<local:OuterGrid>
    <!-- outer grid that should receive the styles -->
    <Grid Grid.Row="1" Grid.Column="1">
        <!-- inner grid,should NOT receive the styles -->
        <TextBlock>inner</TextBlock>
    </Grid>
</local:OuterGrid>

或者在不使用 Grid 的情况下指定自定义 Style 的默认值:

public class OuterGrid : Grid
{
    public OuterGrid()
    {
        Margin = new Thickness(10);
    }
}

恐怕在 XAML 中没有 CSS 子选择器 (>) 的概念。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...