WPF DataGrid Control Auto-Generated Columns


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

This post follows from the previous post called WPF DataGrid Control Revisited.

Below is the XAML code.

<Window x:Class="DataGridAutoGenCols.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:DataGridAutoGenCols"
        mc:Ignorable="d"
        WindowStartupLocation="CenterScreen"
        Loaded="Window_Loaded"
        Title="DataGridAutoGenCols" Height="250" Width="400">
    <Grid>
        <DataGrid Name="dataGrid">

        </DataGrid>
    </Grid>
</Window>

Below is the code-behind in C#.

using System.Windows;
namespace DataGridAutoGenCols
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            // the loading of data also works here (instead of Window_Loaded)

        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {   // don't forget Loaded="Window_Loaded" in XAML

            // load data
            dataGrid.ItemsSource = new Customer[]
            {
                new Customer { FirstName = "Bob", Gender = Gender.Male },
                new Customer { FirstName = "Sally", Gender = Gender.Female },
                new Customer { FirstName = "Billy", Gender = Gender.Male }
            };
        }
    }
    public class Customer
    {
        public string FirstName { get; set; }
        public Gender Gender { get; set; }
    }
    public enum Gender
    {
        Male,
        Female
    }
}
Series Navigation<< WPF DataGrid Control RevisitedWPF Weather API with DataGrid >>