Monday, April 18, 2016

WPF - How to bind custom class in a DataGrid?

It is the way binding a custom class to a WPF GataGrid.

1. Add the DataGrid on the Window.

2. Add the columns in the DataGrid.

3. Bind a custom property in the columns of the DataGrid
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<Window x:Class="BindingCustomClassToDataGrid.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">
    <Grid>
        <DataGrid AutoGenerateColumns="False" Name="dataGrid1">
            <DataGrid.Columns>
                <DataGridTextColumn Header="ID" Binding="{Binding ID}"/>
                <DataGridTextColumn Header="Name" Binding="{Binding UserName}"/>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>

4. Add the Loaded Event of the Window.

5. Type below codes in the Window Loaded Event.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace BindingCustomClassToDataGrid
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            List<CustomClass> list = new List<CustomClass>();
            list.Add(new CustomClass { ID = "ID-01", UserName = "Name-01" });
            list.Add(new CustomClass { ID = "ID-02", UserName = "Name-02" });
            list.Add(new CustomClass { ID = "ID-03", UserName = "Name-03" });
            list.Add(new CustomClass { ID = "ID-04", UserName = "Name-04" });

            dataGrid1.ItemsSource = list;
        }
    }
}

6. Below image is result.

※ You can refer the below video.

No comments:

Post a Comment