给定此示例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>
我如何样式化TabItem
的所有直接Grid
子,而不是层次结构中更深的其他Grid
?
这是我所尝试的(我把它放在App.xml
):
<Style TargetType="TabItem">
<Style.Resources>
<Style TargetType="Grid">
<Setter Property="Margin" Value="10" />
</Style>
</Style.Resources>
</Style>
(我知道我可以使用Style={StaticResource ...}
分配某些样式,但我必须将其单独应用于所有Grid
,这似乎是许多不必要的代码…)
我如何样式化
TabItem
的所有直接Grid
子,而没有其他Grid
在层次结构中更深?
通过显式地为所有外部Grid
元素设置Style
属性。
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子选择器(>
)的概念。