listview - UWP:ListView 无法在中心对齐项目
问题描述
我正在尝试用 ListView 替换我的 StackPanel 以使 ItemClick 功能可用。
但是,我发现当我从 StackPanel 切换到 ListView 时,Item 不再处于中心位置。
之后(列表视图):
这是代码:
<SplitView.Pane>
<Grid Background="{ThemeResource SideBackground}">
<Border BorderBrush="#E8E8E8" BorderThickness="0,0,1,0"/>
<Image x:Name="StoreLogo" Width="32" Height="32"></Image>
<ListView>
<localui:ButtonWithIcon
IconContent=""
Content="书架"
Style="{StaticResource TransparentFontButtonStyle}"/>
<localui:ButtonWithIcon
IconContent=""
Content="搜索"
Style="{StaticResource TransparentFontButtonStyle}"/>
<localui:ButtonWithIcon
IconContent=""
Content="设置"
Style="{StaticResource TransparentFontButtonStyle}"/>
</ListView>
<localui:ButtonWithIcon
IconContent=""
Content="请登录"
VerticalAlignment="Bottom"
Margin="0,0,0,30"
Style="{StaticResource RoundFontButtonStyle}"/>
</Grid>
</SplitView.Pane>
<Style x:Key="TransparentFontButtonStyle" TargetType="localui:ButtonWithIcon">
<Setter Property="Background" Value="Transparent"/>
<Setter Property="BorderBrush" Value="Transparent"/>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="FontSize" Value="30"/>
<Setter Property="HorizontalAlignment" Value="Center"/>
<Setter Property="Margin" Value="0,30,0,0"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="localui:ButtonWithIcon">
<StackPanel>
<TextBlock
x:Name="Icon"
Text="{Binding IconContent, RelativeSource={RelativeSource TemplatedParent}}"
HorizontalAlignment="Center"
FontFamily="{StaticResource SymbolThemeFontFamily}"
FontSize="30"/>
<TextBlock
x:Name="Text"
Text="{TemplateBinding Content}"
HorizontalAlignment="Center"
FontSize="14"
Margin="0,18,0,0"/>
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
解决方案
您需要HorizontalContentAlignment
使用以下代码设置 ListViewItem 的属性。那么 ListViewItem 的内容将居中。
<ListView>
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"></Setter>
</Style>
</ListView.ItemContainerStyle>
<local:ButtonWithIcon Content="书架" IconContent="" />
<local:ButtonWithIcon Content="搜索" IconContent="" />
<local:ButtonWithIcon Content="设置" IconContent="" />
</ListView>
设置上述样式后,ItemContainer
请记住HorizontalAlignment
内部每个元素的属性ListView
。
也就是说,如果<local:ButtonWithIcon>
已设置HorizontalAlignment="Center"
,那么它将使项目保持在中心,如果将其设置为,Stretch
则内部元素ListView
将尝试水平占用所有可用空间。如果未设置,则元素(在您的情况下为 ButtonWithIcon)将粘在左侧。
推荐阅读
- c++ - Qt - 如何正确更改图表
- bash - 在脚本中组合不同的 shell 命令
- vue.js - VUE 3:卡片组件,点击时弹出,弹出根据选择的卡片呈现不同的内容
- android - 在另一个活动之上创建透明活动的问题
- vb.net - 有人熟悉通过 webapi 在 RightFax 中添加用户代表吗?
- python - 在 docker 容器上工作时打开文本文件
- firebase - 发生异常。NoSuchMethodError(NoSuchMethodError:在 null 上调用了方法“[]”。接收方:null 尝试调用:[](“id”))
- build.gradle - AndroidStudio 在模块中发现重复的类
- javascript - 响应性无法正常工作,但仅在横向模式下的移动设备上
- python - 破折号情节引导数字输入放置