GridView in WPF - How to use it?

Learn gridview in wpf - how to use it? with practical examples, diagrams, and best practices. Covers c#, wpf, gridview development techniques with visual explanations.

Mastering GridView in WPF: A Comprehensive Guide to Data Display

Hero image for GridView in WPF - How to use it?

Explore the power of GridView in WPF to efficiently display tabular data. This guide covers setup, data binding, customization, and best practices for creating dynamic and user-friendly interfaces.

The GridView is a powerful and flexible control in Windows Presentation Foundation (WPF) used primarily within a ListView to display collections of data in a tabular format. Unlike the more complex DataGrid, GridView offers a lighter-weight solution for presenting data with customizable columns, headers, and basic sorting capabilities. This article will guide you through the process of implementing and customizing GridView in your WPF applications, from basic setup to advanced styling and data binding techniques.

Understanding the GridView Structure

At its core, GridView defines how items in a ListView are presented. It doesn't directly hold data but rather provides a view for the ListView's ItemsSource. Each column in a GridView is represented by a GridViewColumn, which allows you to specify the header, width, and the data binding path for the content displayed in that column. This separation of concerns makes GridView highly adaptable.

flowchart TD
    A[ListView] --> B{View Property}
    B --> C[GridView]
    C --> D[GridViewColumn 1]
    C --> E[GridViewColumn 2]
    C --> F[...]
    D --> G["DisplayMemberBinding / CellTemplate"]
    E --> H["DisplayMemberBinding / CellTemplate"]
    G --> I[Data Item Property]
    H --> J[Data Item Property]

Conceptual structure of ListView with GridView

Basic Implementation and Data Binding

To get started with GridView, you'll typically embed it within a ListView control in your XAML. The ListView's ItemsSource property will be bound to a collection of objects, and each GridViewColumn will then bind to a specific property of those objects. Let's look at a simple example where we display a list of Person objects.

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}

public partial class MainWindow : Window
{
    public ObservableCollection<Person> People { get; set; }

    public MainWindow()
    {
        InitializeComponent();
        People = new ObservableCollection<Person>
        {
            new Person { FirstName = "John", LastName = "Doe", Age = 30 },
            new Person { FirstName = "Jane", LastName = "Smith", Age = 24 },
            new Person { FirstName = "Peter", LastName = "Jones", Age = 45 }
        };
        this.DataContext = this;
    }
}

C# code for the Person class and MainWindow ViewModel

<ListView ItemsSource="{Binding People}">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="First Name" DisplayMemberBinding="{Binding FirstName}" Width="100"/>
            <GridViewColumn Header="Last Name" DisplayMemberBinding="{Binding LastName}" Width="100"/>
            <GridViewColumn Header="Age" DisplayMemberBinding="{Binding Age}" Width="50"/>
        </GridView>
    </ListView.View>
</ListView>

XAML for a basic ListView with GridView and data binding

Customizing GridView Columns with CellTemplate

While DisplayMemberBinding is convenient for simple text display, you often need more control over how data is rendered within a cell. This is where CellTemplate comes in. By defining a DataTemplate for a GridViewColumn's CellTemplate, you can embed any WPF control (e.g., TextBlock, Image, Button) and apply custom styling or logic.

<ListView ItemsSource="{Binding People}">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Full Name">
                <GridViewColumn.CellTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <TextBlock Text="{Binding FirstName}" FontWeight="Bold" Margin="0,0,5,0"/>
                            <TextBlock Text="{Binding LastName}"/>
                        </StackPanel>
                    </DataTemplate>
                </GridViewColumn.CellTemplate>
            </GridViewColumn>
            <GridViewColumn Header="Status">
                <GridViewColumn.CellTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <Ellipse Width="10" Height="10" Margin="0,0,5,0">
                                <Ellipse.Fill>
                                    <Binding Path="Age">
                                        <Binding.Converter>
                                            <local:AgeToColorConverter/>
                                        </Binding.Converter>
                                    </Binding>
                                </Ellipse.Fill>
                            </Ellipse>
                            <TextBlock Text="{Binding Age}"/>
                        </StackPanel>
                    </DataTemplate>
                </GridViewColumn.CellTemplate>
            </GridViewColumn>
        </GridView>
    </ListView.View>
</ListView>

XAML demonstrating custom CellTemplates for GridViewColumns

using System;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Media;

namespace WpfApp
{
    public class AgeToColorConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is int age)
            {
                return age < 30 ? Brushes.Green : Brushes.OrangeRed;
            }
            return Brushes.Gray;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}

C# code for a simple IValueConverter to change color based on age

Styling and Advanced Features

Styling GridView and its components can be achieved through various WPF styling mechanisms. You can target ListViewItem to style rows, GridViewColumnHeader for column headers, and even individual elements within CellTemplates. While GridView itself doesn't offer built-in sorting or grouping, these features can be implemented by manipulating the ListView's ItemsSource or using ICollectionView.

1. Styling ListViewItem (Rows)

To style the entire row, you apply a Style to the ListViewItem within the ListView's ItemContainerStyle. This allows you to change background colors, add borders, or define triggers for selection states.

2. Styling GridViewColumnHeader

Column headers can be styled by targeting GridViewColumnHeader in a Style within the ListView's Resources or globally. This is useful for custom fonts, colors, or adding interactive elements like sort indicators.

3. Implementing Sorting

Sorting in GridView is typically achieved by handling the Click event of GridViewColumnHeader and then re-sorting the underlying ItemsSource collection (e.g., using ICollectionView or LINQ) and refreshing the ListView.