Center aligning GridView items in last row

我是研究僧i 提交于 2019-12-30 11:31:33

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/46489443/center-aligning-gridview-items-in-last-row

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!