WPF DataGrid Control Tutorial Sample – Qikkwit


This Qikkwit tutorial will explain with samples how WPF DataGrid control is designed to display tables of data in a cohesive format. Developer can add columns manually to WPF DataGrid control, or it will automatically create appropriate columns for your data grid based on the schema of the data source.

How to Bind Data source to WPF data grid

All datasources implementing IEnumerable interface can be bound to grid’s ItemSource property. Grid will automatically generate columns and rows for the data source bound. You can also set DataContext of grid to the data source in XAML.

Data grid binding sample code:

dataGrid1.ItemsSource = myCustomersBinding;

<Grid DataContext=”{StaticResource CustomersViewSource}”>

For changes in the collection to be updated automatically in the DataGrid control, the collection to which the DataGrid control is bound must implement INotifyCollectionChanged, such as ObservableCollection. For changes to property values to be reflected in real time, the bound properties must implement INotifyPropertyChanged.

Developers can directly bind ADO.net data source through Data Source window. Just drag drop the datatable in front of which DataGrid is shown in the designer window. If AutoGeneratingColumns property of data grid is true then it generates columns for properties automatically.

Following are the auto generated columns:

DataType Column Type
Boolean DataGridCheckboxColumn
String DataGridTextBoxColumn
Enum DataGridComboBoxColumn
Uri DataGridHyperlinkColumn

If you don’t want them to generate automatically then just set the property to false.




How to define custom data grid column?

You can use DataGridTemplateColumn class to define your own column. It gives two properties HeaderTemplate and CellTemplate for defining Column headers and cells respectively. CellEditingTemplate will provide DataTemplate when Cell is under editing. Developers can define these WPF grid data templates in resources of Window and apply them wherever necessary. All these templates can also be selected dynamically by respective template selectors.

      <!--Custom column that shows the published date-->
      <DataGridTemplateColumn Header="Contact Name" CellTemplate="{StaticResource DateTemplate}" CellEditingTemplate="{StaticResource EditingDateTemplate}" />

How to show additional data when row is selected?

If developers want to display some row data only when that row is selected in data grid then RowDetailsTemplate and related RowDetailsTemplateSelector is used.

Leave a Reply

Your email address will not be published. Required fields are marked *