How do I bind a List<CustomObject> to a WPF DataGrid?
I'm new to WPF and want to do some basic databinding. I have a List of a CustomObject and want to bind it to a DataGrid.
MainWindow.xaml.cs
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 WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
List<ArticleItem> list = new List<ArticleItem>()
{
new ArticleItem(){ ID=3, Title="test", ViewCount=5},
new ArticleItem(){ ID=3, Title="test", ViewCount=5},
new ArticleItem(){ ID=3, Title="test", ViewCount=5},
new ArticleItem(){ ID=3, Title="test", ViewCount=5},
};
}
}
public class ArticleItem
{
public int ID { get; set; }
public int ViewCount { get; set; }
public String Title { get; set; }
}
}
This is how my grid looks like:
<DataGrid Height="179" HorizontalAlignment="Left" Margin="54,65,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="382">
<DataGrid.Columns>
<DataGridTextColumn Header="ID"/>
<DataGridTextColumn Header="ViewCount" />
<DataGridTextColumn Header="Title" />
</DataGrid.Columns>
</DataGrid>
I'm used to the databinding from ASP.Net, where I can easily say:
this.dataGrid1.DataSource = list;
How must I proceed in WPF?
Solution 1:
if you do not expect that your list
will be recreated then you can use the same approach as you've used for Asp.Net (instead of DataSource
this property in WPF is usually named ItemsSource
):
this.dataGrid1.ItemsSource = list;
But if you would like to replace your list
with new collection instance then you should consider using databinding
.
Solution 2:
You should do it in the xaml code:
<DataGrid ItemsSource="{Binding list}" [...]>
[...]
</DataGrid>
I would advise you to use an ObservableCollection
as your backing collection, as that would propagate changes to the datagrid, as it implements INotifyCollectionChanged
.