#c# #xaml #uwp #windows-10 #windows-10-universal
#c# #xaml #uwp #windows-10 #windows-10-универсальная
Вопрос:
Как я могу сделать так, чтобы заголовок сводных / вкладок для каждой отдельной вкладки был одинаковой ширины и растягивался на всю ширину сводного заголовка, а не выходил за пределы экрана (особенно для мобильных устройств)? Мне еще предстоит найти пример того, как это сделать.
Вот чего я пытаюсь достичь:
Комментарии:
1. Вы проверяли образец UWP
2. Да, но в нем не было примера сводных вкладок на всю ширину экрана.
Ответ №1:
Как я могу сделать так, чтобы заголовок сводных / вкладок для каждой отдельной вкладки был одинаковой ширины и растягивался на всю ширину
Возможно, это невозможно реализовать, просто установив стиль pivot. Но это может быть легко реализовано с помощью класса ViewTreeHelper. Мы можем попытаться вычислить ширину каждого элемента заголовка на actualwidth
основе сводного заголовка и общего количества элементов заголовка. И установите ширину вручную, тогда элементы заголовка будут растягиваться на всю ширину.
Пример кода, подобный следующему:
<Pivot x:Name="CustomPivot">
<Pivot.Resources>
<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="Gray" />
<Setter Property="Foreground" Value="{ThemeResource SystemControlForegroundBaseMediumBrush}" />
<Setter Property="Padding" Value="{ThemeResource PivotHeaderItemMargin}" />
<Setter Property="Height" Value="Auto" />
<Setter Property="VerticalContentAlignment" Value="Center" />
<Setter Property="IsTabStop" Value="False" />
<Setter Property="RequestedTheme" Value="Dark" />
<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"
BasedOn="{StaticResource BaseContentPresenterStyle}"
TargetType="ContentPresenter">
<Setter Property="FontFamily" Value="{ThemeResource PivotHeaderItemFontFamily}" />
<Setter Property="FontWeight" Value="{ThemeResource PivotHeaderItemThemeFontWeight}" />
<Setter Property="FontSize" Value="{ThemeResource PivotHeaderItemFontSize}" />
</Style>
</Grid.Resources>
<ContentPresenter
x:Name="ContentPresenter"
Margin="{TemplateBinding Padding}"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
FontFamily="{TemplateBinding FontFamily}"
FontSize="{TemplateBinding FontSize}"
FontWeight="{TemplateBinding FontWeight}"
Content="{TemplateBinding Content}"
ContentTemplate="{TemplateBinding ContentTemplate}">
<ContentPresenter.RenderTransform>
<TranslateTransform x:Name="ContentPresenterTranslateTransform" />
</ContentPresenter.RenderTransform>
</ContentPresenter>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="SelectionStates">
<VisualStateGroup.Transitions>
<VisualTransition
From="Unselected"
GeneratedDuration="0:0:0.33"
To="UnselectedLocked" />
<VisualTransition
From="UnselectedLocked"
GeneratedDuration="0:0:0.33"
To="Unselected" />
</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
Duration="0"
Storyboard.TargetName="ContentPresenterTranslateTransform"
Storyboard.TargetProperty="X"
To="{ThemeResource PivotHeaderItemLockedTranslation}" />
<DoubleAnimation
Duration="0"
Storyboard.TargetName="ContentPresenter"
Storyboard.TargetProperty="(UIElement.Opacity)"
To="0" />
</Storyboard>
</VisualState>
<VisualState x:Name="Selected">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Foreground">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightAltBaseHighBrush}" />
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="Grid" Storyboard.TargetProperty="Background">
<DiscreteObjectKeyFrame KeyTime="0" Value="#FF42424C" />
</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>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Pivot.Resources>
<PivotItem>
<PivotItem.Header>
<local:TabHeader Glyph="amp;#xE719;" Label="item 1" />
</PivotItem.Header>
<TextBlock Text="Content content content" />
</PivotItem>
<PivotItem>
<PivotItem.Header>
<local:TabHeader Glyph="amp;#xE721;" Label="item 2" />
</PivotItem.Header>
<TextBlock Text="Content content content" />
</PivotItem>
<PivotItem>
<PivotItem.Header>
<local:TabHeader Glyph="amp;#xE723;" Label="item 3" />
</PivotItem.Header>
<TextBlock Text="Content content content" />
</PivotItem>
</Pivot>
Код, лежащий в основе:
private static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
if (depObj != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i )
{
DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
if (child != null amp;amp; child is T)
{
yield return (T)child;
}
foreach (T childOfChild in FindVisualChildren<T>(child))
{
yield return childOfChild;
}
}
}
}
private void Page_Loaded(object sender, RoutedEventArgs e)
{
IEnumerable<PivotHeaderPanel> headerpanel = FindVisualChildren<PivotHeaderPanel>(CustomPivot);
double totalwidth = headerpanel.ElementAt<PivotHeaderPanel>(0).ActualWidth;
IEnumerable<PivotHeaderItem> items = FindVisualChildren<PivotHeaderItem>(CustomPivot);
int headitemcount = items.Count();
for (int i = 0; i < headitemcount; i )
{
items.ElementAt<PivotHeaderItem>(i).Width = totalwidth / headitemcount;
}
}
Для получения кода пользовательского элемента управления, TabHeader
пожалуйста, обратитесь к официальному образцу.
Комментарии:
1. Я заставил это работать, но только когда окно свернуто до области, которую оно занимает по всей ширине. Есть ли какой-либо стиль или сводный ресурс, который вы использовали для достижения этого результата?
2. @JoeyH, я просто добавляю немного стиля в настройке цветов, чтобы помочь вам четко видеть границу. Стиль не должен влиять на ширину. Я не уверен, что здесь вы имеете в виду под минимизацией, на мой взгляд, это означает, что главное окно приложения должно быть сведено к панели инструментов. Если вы имеете в виду, что при изменении размера окна ширина не будет занимать всю ширину, пожалуйста, поместите вышеупомянутый метод в событие Window.SizeChanged . Но я все равно загрузил свой стиль в ответ, на который вы можете сослаться.
3. Мне неприятно снова беспокоить вас по поводу этой проблемы, но я попробовал это снова в новом проекте, но ни одна из ширины вкладок не перемещается должным образом. Я использовал код из сводного примера Microsoft Samples для проекта. Я не понимаю, что я делаю не так. i.imgur.com/x7A4rXj.png
4. @JoeyH, имеет ли образец свой собственный стиль, нарушающий это. Какая у вашего uwp-приложения целевая версия? Загрузите весь проект, чтобы я мог напрямую помогать в отладке.
5. Целевая версия — 10586, и вот проект: 1drv.ms/u/s !AjzDfXpW-m-skcJR31KsfYdS0ldz0A