适用于第一个孩子的风格?

Tow*_*wer 6 c# wpf xaml

有没有办法将样式应用于容器的第一个(或最后一个或第n个)子项(包含子项的任何东西)?我正在尝试自定义选项卡项的外观,以便第一个选项卡具有与其他项不同的边框半径.

这就是我现在拥有的:

<ControlTemplate TargetType="{x:Type TabItem}">
    <Grid>
        <Border Name="Border" BorderBrush="#666" BorderThickness="1,1,1,0" CornerRadius="8,8,0,0" Margin="0,0,0,-1">
            <TextBlock x:Name="TabItemText" Foreground="#444" Padding="6 2" TextOptions.TextFormattingMode="Display">
                <ContentPresenter x:Name="ContentSite" VerticalAlignment="Center" HorizontalAlignment="Center" ContentSource="Header" Margin="12,2,12,2"/>
            </TextBlock>
        </Border>
    </Grid>
</ControlTemplate>
Run Code Online (Sandbox Code Playgroud)

Lee*_*ger 6

对于ItemsControl派生类(如TabControl),可以使用ItemContainerStyleSelector依赖项属性.设置此依赖项属性后,ItemsControl将为控件中的每个项调用StyleSelector.SelectStyle().这将允许您为不同的项目使用不同的样式.

以下示例更改TabControl中的最后一个选项卡项,因此其文本为粗体,比其他选项卡略大.

首先,新的StyleSelector类:

class LastItemStyleSelector : StyleSelector
{
    public override Style SelectStyle(object item, DependencyObject container)
    {
        var itemsControl = ItemsControl.ItemsControlFromItemContainer(container);
        var index = itemsControl.ItemContainerGenerator.IndexFromContainer(container);

        if (index == itemsControl.Items.Count - 1)
        {
            return (Style)itemsControl.FindResource("LastItemStyle");
        }

        return base.SelectStyle(item, container);
    }
}
Run Code Online (Sandbox Code Playgroud)

此样式选择器将返回带有"LastItemStyle"键的样式,但仅适用于控件中的最后一项.其他项目将使用默认样式.(注意,此函数仅使用ItemsControl中的成员.它还可以用于其他ItemsControl派生类.)接下来,在您的XAML中,首先需要创建两个资源.第一个资源是LastItemStyleSelector,第二个资源是样式.

<Window.Resources>
    <local:LastItemStyleSelector x:Key="LastItemStyleSelector" />

    <Style x:Key="LastItemStyle" TargetType="TabItem">
        <Setter Property="FontWeight" Value="Bold" />
        <Setter Property="FontSize" Value="16" />
    </Style>
</Window.Resources>
Run Code Online (Sandbox Code Playgroud)

最后你的TabControl:

    <TabControl ItemContainerStyleSelector="{StaticResource LastItemStyleSelector}">
        <TabItem Header="First" />
        <TabItem Header="Second" />
        <TabItem Header="Third" />
    </TabControl>
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅MSDN文档: