直接子元素的样式



给定此示例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子选择器(>)的概念。

最新更新