Skip to content

Latest commit

 

History

History
236 lines (186 loc) · 17.2 KB

File metadata and controls

236 lines (186 loc) · 17.2 KB
-api-id -api-type
T:Microsoft.UI.Xaml.Controls.GridView
winrt class

Microsoft.UI.Xaml.Controls.GridView

-description

Represents a control that displays data items in rows and columns.

-xaml-syntax

<GridView .../>
-or-
<GridView ...>
  oneOrMoreItems
</GridView>

-remarks

Tip

For more info, design guidance, and code examples, see List view and grid view.

Use a GridView to display a collection of items in rows and columns that can scroll vertically. Data is stacked horizontally until it fills the columns, then continues with the next row. It's often used when you need to show a rich visualization of each item that takes more space, such as a photo gallery.

Grid view control

GridView is an ItemsControl, so it can contain a collection of items of any type. To populate the view, add items to the Items collection, or set the ItemsSource property to a data source.

By default, a data item is displayed in the GridView as the string representation of the data object it's bound to. To specify exactly how items in the GridView are displayed, you create a DataTemplate to define the layout of controls used to display an individual item. The controls in the layout can be bound to properties of a data object, or have content defined inline. You assign the DataTemplate to the ItemTemplate property of the GridView. For common templates you can use in your app, see Item templates for GridView.

If you populate the GridView by setting the ItemsSource property, the ItemTemplate is applied to every item. If you populate the Items collection directly, the ItemTemplate is applied only if the item is not a GridViewItem. In this example, the template is applied to the first item, but not the second item.

<GridView>
    <GridView.ItemTemplate>
        <DataTemplate>
            <Grid>
                <Border Background="LightGray" Height="200" Width="200">
                    <TextBlock Text="{Binding}" 
                               FontSize="48" Foreground="Green"/>
                </Border>
            </Grid>
        </DataTemplate>
    </GridView.ItemTemplate>
    <GridView.Items>
        <x:String>One</x:String>
        <GridViewItem>Two</GridViewItem>
    </GridView.Items>
</GridView>

If you use the GridView to display large sets of data, see Optimize ListView and GridView for tips to maintain a smooth and responsive user experience.

Note

By default, instead of performing selection, an active pen scrolls/pans a list (like touch, touchpad, and passive pen). If your app should use an active pen for text selection, you can override the pen scrolling behavior. See the Pen interaction section of the Scroll​Viewer class reference for details.

By default, a user can select a single item in a GridView. You can set the SelectionMode property to a ListViewSelectionMode enumeration value to allow multi-selection or to disable selection. You can also change the GridView interaction mode to make items respond to a user click like a button instead of being selected.

This table shows the ways a user can interact with a GridView, and how you can respond to the interaction.

To enable this interaction: Use these settings: Handle this event: Use this property to get the selected item:
No interaction SelectionMode = None, IsItemClickEnabled = False N/A N/A
Single selection SelectionMode = Single, IsItemClickEnabled = False SelectionChanged SelectedItem, SelectedIndex
Contiguous multi-selection SelectionMode = Multiple, IsItemClickEnabled = False SelectionChanged SelectedItems
Non-contiguous multi-selection SelectionMode = Extended, IsItemClickEnabled = False SelectionChanged SelectedItems
Click SelectionMode = None, IsItemClickEnabled = True ItemClick N/A

Note

The PointerWheelChanged event does not bubble up from a GridView. This means that a control that has a GridView inside of it does not receive mouse wheel change messages if the pointer is over the GridView. For example, if you put a GridView inside of a ScrollViewer, you can't scroll the ScrollViewer with the mouse wheel when the pointer is over the GridView.

Note

When you set the Padding property on a GridView control, the value for right padding is ignored; only the values for left, top, and bottom padding are applied.

GridView supports data virtualization to improve performance with large data sets. Random access virtualization is supported when the data source implements the appropriate interfaces, which vary depending on the programming language:

Windows 8 In Windows 8, when the data item in a selected GridViewItem is replaced, the SelectedIndex value is not cleared. In Windows 8.1 or later, the SelectedIndex value is cleared.

GridView implements the ISemanticZoomInformation interface, so it can be used as a view in a SemanticZoom control. When it's used in a SemanticZoom control, always set the ScrollViewer.IsHorizontalScrollChainingEnabled attached property to false on the ScrollViewer that's in the GridView's control template, like this: <GridView ScrollViewer.IsHorizontalScrollChainingEnabled="False">. These members have an effect only when the GridView is hosted in a SemanticZoom control: IsActiveView, IsZoomedInView, SemanticZoomOwner, CompleteViewChange, CompleteViewChangeFrom, CompleteViewChangeTo, InitializeViewChange, MakeVisible, StartViewChangeFrom, StartViewChangeTo.

The default template for GridView includes existing transition animations. Specifically, the default ItemContainerTransitions value already contains values for AddDeleteThemeTransition, ContentThemeTransition, ReorderThemeTransition and EntranceThemeTransition (with IsStaggeringEnabled="False"). If you are setting a new value for ItemContainerTransitions on GridView, consider reproducing these same theme animations as a starting point. If you are setting the property yourself, those defaults get overwritten unless you include them again in your definition.

If you need to handle pointer events for a UIElement in a scrollable view (such as a ScrollViewer), you must explicitly disable support for manipulation events on the element in the view by calling UIElement.CancelDirectmanipulation(). To re-enable manipulation events in the view, call UIElement.TryStartDirectManipulation.

Selection behavior and CollectionViewSource

List controls that derive from Selector have a default selection behavior that depends on what the items source is (the type that's used for ItemsSource). If the items source is a CollectionViewSource instance, then the behavior in the selection control is that the selection will default to the current item. When the list is first displayed, the selection defaults to the first item as current item. If you don't want the first item to be selected in this case, set IsSynchronizedWithCurrentItem to false in the GridView.

-examples

Tip

For more info, design guidance, and code examples, see List view and grid view.

[!div class="nextstepaction"] Open the WinUI 3 Gallery app and see the GridView in action

The WinUI 3 Gallery app includes interactive examples of most WinUI 3 controls, features, and functionality. Get the app from the Microsoft Store or get the source code on GitHub.

Here, a GridView is bound to a grouped CollectionViewSource named cvsProjects. The appearance of individual items in each group is defined by the ItemTemplate. The ItemsPanel specifies how the groups are arranged in the GridView. The GroupStyle.Panel specifies how individual items are arranged within each group. The GroupStyle.ContainerStyle is used to add a border around each group, and set its minimum size and margins. The HidesIfEmpty property is set to true to hide any empty groups.

<Page
    x:Class="GroupedGridViewApp.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:GroupedGridViewApp"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Page.Resources>
        <CollectionViewSource x:Name="cvsProjects" IsSourceGrouped="True" 
                              ItemsPath="Activities"/>
    </Page.Resources>

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <GridView ItemsSource="{Binding Source={StaticResource cvsProjects}}" MaxHeight="500">
            <GridView.ItemTemplate>
                <DataTemplate>
                    <StackPanel Margin="20">
                        <TextBlock Text="{Binding Name}" FontWeight="Bold" 
                                   Style="{StaticResource BaseTextBlockStyle}"/>
                        <TextBlock Text="{Binding DueDate}" TextWrapping="NoWrap" 
                                   Style="{StaticResource BodyTextBlockStyle}" />
                        <CheckBox Content="Complete" IsChecked="{Binding Complete}" 
                                  IsEnabled="False"/>
                    </StackPanel>
                </DataTemplate>
            </GridView.ItemTemplate>
            <GridView.ItemsPanel>
                <ItemsPanelTemplate>
                    <ItemsWrapGrid MaximumRowsOrColumns="3"/>
                </ItemsPanelTemplate>
            </GridView.ItemsPanel>

            <GridView.GroupStyle>
                <GroupStyle HidesIfEmpty="True">
                    <GroupStyle.HeaderTemplate>
                        <DataTemplate>
                            <Grid Background="LightGray" Margin="0">
                                <TextBlock Text='{Binding Name}' 
                                           Foreground="Black" Margin="12"
                                           Style="{StaticResource HeaderTextBlockStyle}"/>
                            </Grid>
                        </DataTemplate>
                    </GroupStyle.HeaderTemplate>
                </GroupStyle>
            </GridView.GroupStyle>
        </GridView>
    </Grid>
</Page>
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Windows.UI.Xaml.Controls;

namespace GroupedGridViewApp
{
    public sealed partial class MainPage : Page
    {
        DateTime startDate = DateTime.Now;

        public MainPage()
        {
            this.InitializeComponent();

            PopulateProjects();
        }

        private void PopulateProjects()
        {
            List<Project> Projects = new List<Project>();

            Project newProject = new Project();
            newProject.Name = "Project 1";
            newProject.Activities.Add(new Activity()
            { Name = "Activity 1", Complete = true, DueDate = startDate.AddDays(4) });
            newProject.Activities.Add(new Activity()
            { Name = "Activity 2", Complete = true, DueDate = startDate.AddDays(5) });
            Projects.Add(newProject);

            newProject = new Project();
            newProject.Name = "Project 2";
            newProject.Activities.Add(new Activity()
            { Name = "Activity A", Complete = true, DueDate = startDate.AddDays(2) });
            newProject.Activities.Add(new Activity()
            { Name = "Activity B", Complete = false, DueDate = startDate.AddDays(3) });
            Projects.Add(newProject);

            newProject = new Project();
            newProject.Name = "Project 3";
            Projects.Add(newProject);

            cvsProjects.Source = Projects;
        }
    }

    public class Project
    {
        public Project()
        {
            Activities = new ObservableCollection<Activity>();
        }

        public string Name { get; set; }
        public ObservableCollection<Activity> Activities { get; private set; }
    }

    public class Activity
    {
        public string Name { get; set; }
        public DateTime DueDate { get; set; }
        public bool Complete { get; set; }
        public string Project { get; set; }
    }
}

-see-also

List view and grid view, ListViewBase, ISemanticZoomInformation, Item templates for GridView, Data binding overview, ListView, SemanticZoom, ListView and GridView sample (Windows 10)