UWP Create border for Pivot Header

Я использую pivot для создания меню с 3 вариантами. Код ниже.

<Pivot x:Name="menuPivot" Margin="0"  SelectedIndex="0" HorizontalAlignment="Center" VerticalAlignment="Center" Grid.Row="1" Grid.ColumnSpan="2" SelectionChanged="ListView_SelectionChanged">

        <PivotItem Header="Day" VerticalAlignment="Center" HorizontalAlignment="Center" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Margin="0,0,10,0" />
        <PivotItem Header="Week" VerticalAlignment="Center" HorizontalAlignment="Center" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Margin="0,0,10,0" />
        <PivotItem Header="Month" VerticalAlignment="Center" HorizontalAlignment="Center" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Margin="-1,0,0,0" Background="#FFFB0000" BorderBrush="{StaticResource currentThemeColor}" />
    </Pivot>

Мне нужно добиться такого вида меню:  введите описание изображения здесь

Пока что я изменил стиль Pivots по умолчанию для заголовка с помощью кода ниже:

<Style TargetType="PivotHeaderItem">
    <Setter Property="FontSize" Value="{ThemeResource PivotHeaderItemFontSize}" />
    <Setter Property="FontFamily" Value="{ThemeResource PivotHeaderItemFontFamily}" />
    <Setter Property="FontWeight" Value="{ThemeResource PivotHeaderItemThemeFontWeight}" />
    <Setter Property="CharacterSpacing" Value="{ThemeResource PivotHeaderItemCharacterSpacing}" />
    <Setter Property="Background" Value="Transparent" />
    <Setter Property="Foreground" Value="Gray" />
    <!-- original value {ThemeResource SystemControlForegroundBaseMediumBrush} -->
    <Setter Property="Padding" Value="{ThemeResource PivotHeaderItemMargin}" />
    <Setter Property="Height" Value="48" />
    <Setter Property="VerticalContentAlignment" Value="Center" />
    <Setter Property="HorizontalContentAlignment" Value="Center" />
    <Setter Property="IsTabStop" Value="False" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="PivotHeaderItem">
                <Grid x:Name="Grid" Background="{TemplateBinding Background}">
                    <Grid.Resources>
                        <Style x:Key="BaseContentPresenterStyle" TargetType="ContentPresenter">
                            <Setter Property="FontFamily" Value="Segoe UI" />
                            <Setter Property="FontWeight" Value="SemiBold" />
                            <Setter Property="FontSize" Value="15" />

                            <Setter Property="TextWrapping" Value="Wrap" />
                            <Setter Property="LineStackingStrategy" Value="MaxHeight" />
                            <Setter Property="TextLineBounds" Value="Full" />
                            <Setter Property="OpticalMarginAlignment" Value="TrimSideBearings" />
                        </Style>
                        <Style x:Key="BodyContentPresenterStyle" TargetType="ContentPresenter" BasedOn="{StaticResource BaseContentPresenterStyle}">
                            <Setter Property="FontFamily" Value="{ThemeResource PivotHeaderItemFontFamily}" />
                            <Setter Property="FontWeight" Value="{ThemeResource PivotHeaderItemThemeFontWeight}" />
                            <Setter Property="FontSize" Value="{ThemeResource PivotHeaderItemFontSize}" />

                        </Style>
                    </Grid.Resources>
                    <VisualStateManager.VisualStateGroups>
                        <VisualStateGroup x:Name="SelectionStates">
                            <VisualStateGroup.Transitions>
                                <VisualTransition From="Unselected" To="UnselectedLocked" GeneratedDuration="0:0:0.33" />
                                <VisualTransition From="UnselectedLocked" To="Unselected" GeneratedDuration="0:0:0.33" />
                            </VisualStateGroup.Transitions>
                            <VisualState x:Name="Disabled">
                                <Storyboard>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Foreground">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlDisabledBaseMediumLowBrush}" />
                                    </ObjectAnimationUsingKeyFrames>
                                </Storyboard>
                            </VisualState>
                            <VisualState x:Name="Unselected" />
                            <VisualState x:Name="UnselectedLocked">
                                <Storyboard>
                                    <DoubleAnimation Storyboard.TargetName="ContentPresenterTranslateTransform" Storyboard.TargetProperty="X" Duration="0" To="{ThemeResource PivotHeaderItemLockedTranslation}" />
                                    <DoubleAnimation Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="(UIElement.Opacity)" Duration="0" To="0" />
                                </Storyboard>
                            </VisualState>
                            <VisualState x:Name="Selected">
                                <Storyboard>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Foreground">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource currentThemeColor}" />
                                        <!-- original value {ThemeResource SystemControlHighlightAltBaseHighBrush} -->
                                    </ObjectAnimationUsingKeyFrames>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="Grid" Storyboard.TargetProperty="Background">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightTransparentBrush}" />
                                    </ObjectAnimationUsingKeyFrames>

                                </Storyboard>
                            </VisualState>
                            <VisualState x:Name="UnselectedPointerOver">
                                <Storyboard>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Foreground">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightAltBaseMediumHighBrush}" />
                                    </ObjectAnimationUsingKeyFrames>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="Grid" Storyboard.TargetProperty="Background">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightTransparentBrush}" />
                                    </ObjectAnimationUsingKeyFrames>
                                </Storyboard>
                            </VisualState>
                            <VisualState x:Name="SelectedPointerOver">
                                <Storyboard>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Foreground">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightAltBaseMediumHighBrush}" />
                                    </ObjectAnimationUsingKeyFrames>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="Grid" Storyboard.TargetProperty="Background">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightTransparentBrush}" />
                                    </ObjectAnimationUsingKeyFrames>
                                </Storyboard>
                            </VisualState>
                            <VisualState x:Name="UnselectedPressed">
                                <Storyboard>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Foreground">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightAltBaseMediumHighBrush}" />
                                    </ObjectAnimationUsingKeyFrames>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="Grid" Storyboard.TargetProperty="Background">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightTransparentBrush}" />
                                    </ObjectAnimationUsingKeyFrames>
                                </Storyboard>
                            </VisualState>
                            <VisualState x:Name="SelectedPressed">
                                <Storyboard>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Foreground">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightAltBaseMediumHighBrush}" />
                                    </ObjectAnimationUsingKeyFrames>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="Grid" Storyboard.TargetProperty="Background">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightTransparentBrush}" />
                                    </ObjectAnimationUsingKeyFrames>
                                </Storyboard>
                            </VisualState>
                        </VisualStateGroup>
                    </VisualStateManager.VisualStateGroups>
                    <ContentPresenter x:Name="ContentPresenter" Content="{TemplateBinding Content}" ContentTemplate="{TemplateBinding ContentTemplate}" Margin="{TemplateBinding Padding}" FontSize="{TemplateBinding FontSize}" FontFamily="{TemplateBinding FontFamily}" FontWeight="{TemplateBinding FontWeight}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}">
                        <ContentPresenter.RenderTransform>
                            <TranslateTransform x:Name="ContentPresenterTranslateTransform" />
                        </ContentPresenter.RenderTransform>
                    </ContentPresenter>

                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

У меня такой вид:  введите описание изображения здесь

Я не могу понять, как добавить границы, подобные тем, что на первом изображении, и как изменить цвет границы выбранного заголовка?

Кроме того, если вы думаете, что это можно сделать более простым способом, используя какой-либо другой элемент управления, кроме Pivot, это также будет полезно.


person alminh    schedule 31.05.2016    source источник


Ответы (2)


Вы можете добавить четыре Border в шаблон PivotHeaderItem следующим образом:

<Style TargetType="PivotHeaderItem">
    <!--...-->
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="PivotHeaderItem">
                <Grid x:Name="Grid" Background="{TemplateBinding Background}" Width="100">
                    <!--...-->
                    <VisualStateManager.VisualStateGroups>
                        <VisualStateGroup x:Name="SelectionStates">
                            <!--...-->
                            <VisualState x:Name="Selected">
                                <Storyboard>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter"
                                       Storyboard.TargetProperty="Foreground">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="Blue" />
                                    </ObjectAnimationUsingKeyFrames>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="Grid"
                                       Storyboard.TargetProperty="Background">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightTransparentBrush}" />
                                    </ObjectAnimationUsingKeyFrames>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="RightLine"
                                       Storyboard.TargetProperty="Width">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="2" />
                                    </ObjectAnimationUsingKeyFrames>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="SelectedLine"
                                       Storyboard.TargetProperty="Background">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="Blue" />
                                    </ObjectAnimationUsingKeyFrames>
                                </Storyboard>
                            </VisualState>
                            <!--...-->
                        </VisualStateGroup>
                    </VisualStateManager.VisualStateGroups>
                    <ContentPresenter x:Name="ContentPresenter" Content="{TemplateBinding Content}" ContentTemplate="{TemplateBinding ContentTemplate}"
                                      Margin="{TemplateBinding Padding}" FontSize="{TemplateBinding FontSize}" FontFamily="{TemplateBinding FontFamily}"
                                      FontWeight="{TemplateBinding FontWeight}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                      VerticalAlignment="{TemplateBinding VerticalContentAlignment}">
                        <ContentPresenter.RenderTransform>
                            <TranslateTransform x:Name="ContentPresenterTranslateTransform" />
                        </ContentPresenter.RenderTransform>
                    </ContentPresenter>
                    <Border x:Name="TopLine" Height="3" Background="Blue" VerticalAlignment="Top" HorizontalAlignment="Stretch" />
                    <Border x:Name="BottomLine" Height="2" Background="LightGray" VerticalAlignment="Bottom" HorizontalAlignment="Stretch" />
                    <Border x:Name="RightLine" Width="1" Background="LightGray" VerticalAlignment="Center"
                            HorizontalAlignment="Right" Height="{TemplateBinding FontSize}" />
                    <Border x:Name="SelectedLine" Height="2" VerticalAlignment="Bottom" HorizontalAlignment="Stretch"
                            Background="LightGray" Margin="15,0,0,0" />
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Я прокомментировал часть кода в этом стиле, чтобы наглядно показать, что я изменил, вы можете видеть, что я дал ширину Grid для тестирования здесь, вы можете удалить это.

Я также изменил визуальное состояние Selected, чтобы изменить передний план заголовка, ширину "Разделителя" и фон моего SelectedLine. Вот изображение моего стиля:

введите здесь описание изображения

person Grace Feng    schedule 01.06.2016
comment
Feng-MSFT Это работает как шарм! Но проблема в том, что у меня есть 2 сводки, одна для меню, а другая для различного контента. Есть ли способ применить этот стиль заголовка только к одной оси? - person alminh; 01.06.2016
comment
@alminh, есть очень простой способ сделать это: вы можете установить Grid элемент управления вне вашего желаемого Pivot и поместить стиль в ресурсы этой сетки. - person Grace Feng; 01.06.2016
comment
@ Feng-MSFT Я хочу выровнять заголовки Pivot по центру страницы UWP. Как этого добиться? Я хочу создать VisualStates, чтобы, если размер экрана больше 900, выровнять их по левому краю, иначе выровнять их по центру. Не могли бы вы помочь. - person iam.Carrot; 30.11.2016

Вы можете развернуть свой собственный элемент управления с помощью сетки столбцов из 3 (или 5, если вы поместите разделители в их собственные столбцы) RadioButtons вверху, чтобы отобразить заголовки. Глядя на шаблон по умолчанию, кажется, что он довольно черный коробка, и вам может быть лучше со своим. Вы также можете просто удалить заголовки из заголовка по умолчанию и создать сетку из 3 столбцов над измененным Pivot.

person Filip Skakun    schedule 31.05.2016
comment
Спасибо за вашу поддержку. Это интересное решение. Я обязательно попробую. - person alminh; 01.06.2016