WPF DataGrid Control Revisited


This entry is part 3 of 6 in the series WPF DataGrid Control

We already have a post on this topic called WPF Data Control.

This control can display multicolumn rows of data that can be sorted, edited and more. This post illustrated how you can use the DataGrid where more of your code is in XAML.

Below is the screenshot of the output of the XAML project called DataGridSimple. It’s actually not simple when you compare it to the C# example in the next post.

Below is the code behind. We must define a class that represents the data that we want to display in the grid. As you can see, it’s intentionally very simple. You add more columns to the Customer later, as needed. Also, because we are using an enumeration, we need to define that as well.

using System.Windows;
namespace DataGridSimple
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }
    public class Customer
    {
        public string FirstName { get; set; }
        public Gender Gender { get; set; }
    }
    public enum Gender
    {
        Male,
        Female
    }
}

Here is the XAML code.

<Window x:Class="DataGridSimple.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:DataGridSimple"
        mc:Ignorable="d"
        Title="DataGridSimple" Height="350" Width="400">
    <Grid>
        <DataGrid IsReadOnly="True"
                  xmlns:local="clr-namespace:DataGridSimple"
                  xmlns:sys="clr-namespace:System;assembly=mscorlib">
            <DataGrid.Resources>
                <ObjectDataProvider x:Key="genderEnum" MethodName="GetValues"
                                    ObjectType="{x:Type sys:Enum}">
                    <ObjectDataProvider.MethodParameters>
                        <x:Type Type="local:Gender"/>
                    </ObjectDataProvider.MethodParameters>
                </ObjectDataProvider>
            </DataGrid.Resources>
            <!-- the columns-->
            <DataGrid.Columns>
                <DataGridTextColumn Header="First Name" Binding="{Binding FirstName}"/>
                <DataGridTextColumn Header="Gender" Binding="{Binding Gender}"/>
            </DataGrid.Columns>
            <!-- the data -->
            <local:Customer FirstName="Bob" Gender="Male"/>
            <local:Customer FirstName="Suzie" Gender="Female"/>
        </DataGrid>
    </Grid>
</Window>
Series Navigation<< WPF DataGrid Control ExampleWPF DataGrid Control Auto-Generated Columns >>