How to Bind WPF Datagrid with List of Objects?

How to Bind WPF Datagrid with List of Objects?

Lets say I have a class in which I have declared properties. I want to make objects of that class and store them in the list and finally bind that list to a WPF datagrid. The ItemSource property of DataGrid is the key to data binding. You can bind any data source that implements IEnuemerable. Each row in the DataGrid is bound to an object in the data source and each column in the DataGrid is bound to a property of the data source objects.

Lets dive in detail for more clear view.

I have created following class

public class Author
{
    public int ID { get; set; }
    public string Name { get; set; }      
    public DateTime DOB { get; set; }
    public string BookTitle { get; set; }
    public bool IsMVP  { get; set; }
}

Now let's create a collection of Author objects by using the List class.

private List LoadCollectionData()
{
    List authors = new List();
    authors.Add(new Author(){
            ID = 101,
            Name = "Mahesh Chand",
            BookTitle = "Graphics Programming with GDI+",
            DOB = new DateTime(1975, 2, 23),
            IsMVP = false });
    authors.Add(new Author()
    {
        ID = 201,
        Name = "Mike Gold",
        BookTitle = "Programming C#",
        DOB = new DateTime(1982, 4, 12),
        IsMVP = true
    });
    authors.Add(new Author()
    {
        ID = 244,
        Name = "Mathew Cochran",
        BookTitle = "LINQ in Vista",
        DOB = new DateTime(1985, 9, 11),
        IsMVP = true
    });
    return authors;
}

Now the last step is to set ItemsSource property of DataGrid. The following code snippet sets the ItemsSource property of a DataGrid to List of Authors.

MyDataGrid.ItemsSource = LoadCollectionData();

I think, you would have understood the concept on binding the list of objects with WPF datagrid ItemsSource property with this simple example.