将最后一行中的 GridView 项目居中对齐 [英] Center aligning GridView items in last row

查看:32
本文介绍了将最后一行中的 GridView 项目居中对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现一个 GridView,它在一行中包含 3 个项目,如果最后一行的项目数是 2,那么最后一行项目应该居中对齐而不是左对齐.这里有几张图片来解释我想要实现的目标.

目前我的实现看起来像

.

这就是我想要实现的目标.

任何帮助将不胜感激.

解决方案

有很多方法可以实现您提到的功能.

总而言之,您需要继承 GridView 并覆盖

然而,这种简单的方式并不能适应所有的场景.

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.

Any help would be appreciated.

解决方案

There are many ways realizing the feature that you mentioned.

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.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆