Different sized tile items in WinRT GridView

GridView in WinRT allows you to arrange tile items in wrap manner. In case, if you want to arrange items as in Windows store app, we need different sized tile items. There is no direct way to configure different sized items while using data binding in Grid View. I am going to explain the solution in this article.

VariableSizedWrapGrid should be the panel for Grid View. This panel has two attached properties ColumnSpan and RowSpan. To set this property to the containers, we have to inherit the GridView class and override the PrepareContainerForItemOverride.

    public class VariableGrid : GridView
    {
        protected override void PrepareContainerForItemOverride(Windows.UI.Xaml.DependencyObject element, object item)
        {
            var tile = item as Model;

            if (tile != null)
            {
                var griditem = element as GridViewItem;

                if (griditem != null)
                {
                    VariableSizedWrapGrid.SetColumnSpan(griditem, tile.ColumnSpan);
                    VariableSizedWrapGrid.SetRowSpan(griditem, tile.RowSpan);
                }
            }

            base.PrepareContainerForItemOverride(element, item);
        }
    }

I have the Model class as below. It contains the ColumnSpan and RowSpan property.

    public class Model
    {
        public int ColumnSpan { get; set; }

        public int RowSpan { get; set; }

        public string Header { get; set; }
    }

Our VariableGrid class will map the span properties from model to containers and you can see the following output.

        <local:VariableGrid ItemsSource="{Binding Models}"
                            Padding="0"
                            Margin="100"
                            Height="630">
            <local:VariableGrid.ItemTemplate>
                <DataTemplate>
                    <Grid Background="MediumOrchid">
                        <TextBlock Text="{Binding Header}"
                                   Margin="10"
                                   HorizontalAlignment="Left"
                                   VerticalAlignment="Bottom" />
                    </Grid>
                </DataTemplate>
            </local:VariableGrid.ItemTemplate>
            <local:VariableGrid.ItemsPanel>
                <ItemsPanelTemplate>
                    <VariableSizedWrapGrid ItemHeight="200"
                                           ItemWidth="200" />
                </ItemsPanelTemplate>
            </local:VariableGrid.ItemsPanel>
        </local:VariableGrid>

Leave a comment

Up ↑