在最后一行中居中对齐GridView项 [英] Center aligning GridView items in last row
问题描述
我想实现一个GridView,它连续接收3个项目,并且如果最后一行中的项目数为2,则最后一行的项目应居中对齐而不是左对齐.这里有一些图片来说明我想要实现的目标.
I want to implement a GridView which takes 3 items in a row, and if the number of items are 2 in last row, then the last row items should be aligned center instead of being left-aligned. Here are a couple of images to explain what I want to achieve.
当前,我的实现看起来像
Currently my implementation looks like
.
这就是我要实现的目标.
And this is what I want to achieve.
任何帮助将不胜感激.
推荐答案
有很多方法可以实现您提到的功能.
There are many ways realizing the feature that you mentioned.
总结起来,您需要继承GridView
并覆盖 MeasureOverride
Rect
小组成员的孩子.这种方式很复杂.有关更多信息,您可以参考
XAML定制面板概述.
To summarize it, you need to inherit GridView
and override MeasureOverride
ArrangeOverride
method to re-calculate each Rect
of Panel's children. This way is complex. For more info you could refer to
XAML custom panels overview.
您还可以使用PrepareContainerForItemOverride
方法直接重新布置项目.
And you could also use PrepareContainerForItemOverride
method to re-layout the item directly.
<local:VariableGrid
x:Name="MyGridView"
SelectionMode="Single"
IsSwipeEnabled="False">
<local:VariableGrid.ItemTemplate >
<DataTemplate>
<StackPanel BorderBrush="Red" BorderThickness="3" Height="200" Width="200" Margin="20">
</StackPanel>
</DataTemplate>
</local:VariableGrid.ItemTemplate>
<local:VariableGrid.ItemsPanel>
<ItemsPanelTemplate>
<VariableSizedWrapGrid
Orientation="Horizontal"
VerticalAlignment="Top"
ScrollViewer.HorizontalScrollMode="Enabled"
ScrollViewer.VerticalScrollMode="Disabled"
MaximumRowsOrColumns="4">
</VariableSizedWrapGrid>
</ItemsPanelTemplate>
</local:VariableGrid.ItemsPanel>
</local:VariableGrid>
VariableGrid.cs
public sealed class VariableGrid : GridView
{
public VariableGrid()
{
this.DefaultStyleKey = typeof(VariableGrid);
}
protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
{
var list = this.ItemsSource as List<string>;
var griditem = element as GridViewItem;
for (var t = ((list.Count - list.Count % 4)); t < list.Count; t++)
{
if (item as string == list[t])
{
if (griditem != null)
{
VariableSizedWrapGrid.SetColumnSpan(griditem, 2);
}
}
}
base.PrepareContainerForItemOverride(element, item);
}
}
但是,这种简单的方法无法适应所有情况.
However, this simple way can not fit all the scenario.
这篇关于在最后一行中居中对齐GridView项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!