GridView Control in Windows 8

While ListBox and ComboBox continue to work in Windows 8, their use is discouraged. They are not designed well for touch input and there are new and more powerful controls in WinRT that you can use instead; specifically the ListView and the GridView. 

ListView and GridView both derive from ListViewBase, and neither adds any properties, methods or events; thus they are nearly identical.  The key difference is that ListView is typically used for vertical scrolling, while GridView makes a grid that is typically scrolled horizontally.

Creating a demo program to illustrate GridView is nearly trivial.  We’ll divide our page’s Grid (not to be confused with GridView) into rows and columns. In the left column we’ll add two buttons: Add and Insert. In the right hand column we’ll add the GridView.

<Grid Background="{StaticResource ApplicationPageBackgroundBrush}">
        <ColumnDefinition Width="1*" />
        <ColumnDefinition Width="3*" />
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*" />
    <Button Name="Add"
    <Button Name="Insert"
            Click="Insert_Click_1" />
    <GridView Name="xGridView"
              Grid.Row="0" />


The event handler for both the add button and the insert button are nearly intuitive,


private int counter = 1;

private void Add_Click_1( object sender, RoutedEventArgs e )
     xGridView.Items.Add( "Item " + counter++ );

 private void Insert_Click_1( object sender, RoutedEventArgs e )
     xGridView.Items.Insert( 0, "Item " + counter++ );

Clicking Add and/or Insert a number of times will fill the first column of the grid, and then the second column will begin to fill.  Unfortunately, the grid will size all the items based on the size of the first item, and things get crowded quickly.  We can fix this by adding a style,

 <GridView Name="xGridView"
           Grid.Row="0" >
         <Style TargetType="ListViewItem">
             <Setter Property="Width"
                     Value="150" />

Now when the grid is populated there is a bit more breathing room between the columns and nothing is truncated,


[Click image for full size]


Special thanks to Ian Griffiths for helping me figure out the styling solution.

About Jesse Liberty

Jesse Liberty has three decades of experience writing and delivering software projects and is the author of 2 dozen books and a couple dozen Pluralsight & LinkedIn Learning courses. He was a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a Xamarin Certified Mobile Developer and a Xamarin MVP and a Microsoft MVP.
This entry was posted in Essentials, Mini-Tutorial, Windows 8 and tagged . Bookmark the permalink.

9 Responses to GridView Control in Windows 8

Comments are closed.