|
WPF DataGrid Control
Introduction
Since .NET 4.0, Microsoft is shipping a DataGrid control that provides all the basic functionality needed, like:
Basic usage: Auto generate columns
To show a basic data grid , just drop a DataGrid control to your view and bind the ItemsSource to a collection of data objects and you're done. The DataGrid provides a feature called AutoGenerateColumns that automatically generates column according to the public properties of your data objects. It generates the following types of columns:
- TextBox columns for string values
- CheckBox columns for boolean values
- ComboBox columns for enumerable values
- Hyperlink columns for Uri values
<DataGrid ItemsSource="{Binding Customers}" />
Manually define columns
Alternatively you can define your columns manually by setting the AutoGenerateColumns property to False. In this case you have to define the columns in the Columns collection of the data grid. You have the following types of columns available:
DataGridCheckBoxColumn for boolean values
DataGridComboBoxColumn for enumerable values
DataGridHyperlinkColumn for Uri values
DataGridTemplateColumn to show any types of data by defining your own cell template
DataGridTextColumn to show text values
<DataGrid ItemsSource="{Binding Customers}" AutoGenerateColumns="False" >
<DataGrid.Columns>
<DataGridTemplateColumn Header="Image" Width="SizeToCells" IsReadOnly="True">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Image Source="{Binding Image}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
Selection
The data grid includes a variety of selection modes. They are configured by the SelectionMode and SelectionUnit property.
- The
SelectionMode can be set to Single or Extended to define if one or multiple units can be selected simultaneously.
- The
SelectionUnit defines the scope of one selection unit. It can be set to Cell, CellAndRowHeader and FullRow.
<DataGrid ItemsSource="{Binding Customers}"
SelectionMode="Extended" SelectionUnit="Cell" />
Column sorting, reordering and resizing
The data grid provides features to sort, reorder and resize columns. They can be enabled or disabled by the following properties:
CanUserReorderColumns enables or disables column re-ordering
CanUserResizeColumns enables or disables column resizing
CanUserResizeRows enables or disables row resizing
CanUserSortColumns enables or disables column sorting
<DataGrid ItemsSource="{Binding Customers}"
CanUserReorderColumns="True" CanUserResizeColumns="True"
CanUserResizeRows="False" CanUserSortColumns="True"/>
Grouping
The data grid also supports grouping. To enable grouping you have to define a CollectionView that contains to least one GroupDescription that defines the criterias how to group.
Customers = new ListCollectionView(_customers);
Customers.GroupDescriptions.Add(new PropertyGroupDescription("Gender"));
Second thing you need to do is defining a template how the groups should look like. You can do this by setting the GroupStyle to something like the following snippet.
<DataGrid ItemsSource="{Binding GroupedCustomers}">
<DataGrid.GroupStyle>
<GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Path=Name}" />
</StackPanel>
</DataTemplate>
</GroupStyle.HeaderTemplate>
<GroupStyle.ContainerStyle>
<Style TargetType="{x:Type GroupItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type GroupItem}">
<Expander>
<Expander.Header>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=Name}" />
<TextBlock Text="{Binding Path=ItemCount}"/>
<TextBlock Text="Items"/>
</StackPanel>
</Expander.Header>
<ItemsPresenter />
</Expander>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</GroupStyle.ContainerStyle>
</GroupStyle>
</DataGrid.GroupStyle>
</DataGrid>
Row Details
The data grid provides a feature that shows a detail panel for a selected row. It can be enabled by setting a DataTemplate to the RowDetailsTemplate property. The data template gets the object that is bound to this row passed by the DataContext and can bind to it.
<DataGrid ItemsSource="{Binding Customers}">
<DataGrid.Columns>
<DataGridTextColumn Header="First Name" Binding="{Binding FirstName}" />
</DataGrid.Columns>
<DataGrid.RowDetailsTemplate>
<DataTemplate>
<Image Height="100" Source="{Binding Image}" />
</DataTemplate>
</DataGrid.RowDetailsTemplate>
</DataGrid>
Row Details depending on the type of data
You can specify a RowDetailsTemplateSelector that selects a data template according to the type or data that this row contains. To do this, create a type that derives from DataTemplateSelector and override the SelectTemplate method. In the items argument you get the data and you can determine which data template to display. Return an instance of that data template as return value.
public class GenderTemplateSelector : DataTemplateSelector
{
public DataTemplate MaleTemplate { get; set; }
public DataTemplate FemaleTemplate { get; set; }
public override DataTemplate SelectTemplate(object item,
DependencyObject container)
{
var customer = item as Customer;
if (customer == null)
return base.SelectTemplate(item, container);
if( customer.Gender == Gender.Male)
{
return MaleTemplate;
}
return FemaleTemplate;
}
}
<l:GenderTemplateSelector x:Key="genderTemplateSelector">
<l:GenderTemplateSelector.MaleTemplate>
<DataTemplate>
<Grid Background="LightBlue">
<Image Source="{Binding Image}" Width="50" />
</Grid>
</DataTemplate>
</l:GenderTemplateSelector.MaleTemplate>
<l:GenderTemplateSelector.FemaleTemplate>
<DataTemplate>
<Grid Background="Salmon">
<Image Source="{Binding Image}" Width="50" />
</Grid>
</DataTemplate>
</l:GenderTemplateSelector.FemaleTemplate>
</l:GenderTemplateSelector>
<DataGrid ItemsSource="{Binding Customers}"
RowDetailsTemplateSelector="{StaticResource genderTemplateSelector}" />
Alternating BackgroundBrush
You can define a an AlternatingRowBackground that is applied every even row. You can additionally specify an AlternationCount if you only want to ink every every n-th data row.
<DataGrid ItemsSource="{Binding Customers}"
AlternatingRowBackground="Gainsboro" AlternationCount="2"/>
Frozen Columns
The data grid also supports the feature to freeze columns. That means they stay visible while you scoll horizontally through all columns. This is a useful feature to keep a referencing column like an ID or a name always visible to keep your orientation while scrolling.
To freeze a numer of columns just set the FrozenColumnCount property to the number of columns you want to freeze.
<DataGrid ItemsSource="{Binding Customers}" FrozenColumnCount="2" />
Headers visbility
You can control the visibility of row and column headers by setting the HeadersVisibility property to either None,Row,Column or All
<DataGrid ItemsSource="{Binding Customers}" HeadersVisibility="None" />
Comments on this article
Show all comments
 |
| Declan | |
|
| Commented on 17.June 2010 |
Great article, just what I needed.
One question though, Is there a 'DataGridDateTimePickerColumn'? Or would I have to write one myself?
|
|
|
 |
| Anthony Wieser | |
|
| Commented on 18.June 2010 |
| Just out of curiousity, why doesn't the GenderTemplateSelector change when you change the sex of an entry?
|
|
|
 |
| Chodu | |
|
| Commented on 20.June 2010 |
| the example has build errors! kahan se maru ise so that it runs???????
|
|
|
 |
| Raghav | |
|
| Commented on 22.June 2010 |
| Very!!! Very!!! helpful.
|
|
|
 |
| Amit Paul... | |
|
| Commented on 29.June 2010 |
| From my point of view this website would one day be a leading WPF tutorial site (like w3schools.com for web technologies) with numerous articles organized in an easy to navigate way. Thank you thousand times for your approach.
|
|
|
 |
| Hiren Solanki | |
|
| Commented on 2.July 2010 |
Hello Mr.Chodu You just go and fuck the things..
Dont roam aroung my site.. we r believing it as Religion and you are just fucking off
|
|
|
 |
| Sans | |
|
| Commented on 2.July 2010 |
| Is it Possible to show the empty rows ??
|
|
|
 |
| venkat | |
|
| Commented on 4.July 2010 |
the tutorial is really good.i am new to WPF and trying to understand the things.can anyone tell me how should i follow the order of tags?i.e. in Grouping the following are used:<DataGrid.GroupStyle>
<GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate>
i want to know how to follow the order.if possible cn anyone gv me link to the site?i am new to WPF...
|
|
|
 |
| Gaurav Dixit | |
|
| Commented on 5.July 2010 |
| Very nice article for beginners.....
|
|
|
 |
| Ali | |
|
| Commented on 7.July 2010 |
Hello,
Thanks a lot...
God bless upon u for this article. U hv written a very good article and a useful too. Such tutorials are needed for newer as well as experienced because of technology changed.
I need Globalization and Localization in WPF (Desktop) article.
Please assist me....
Again Thanks a lot ...
|
|
|
 |
| Jeumelled | |
|
| Commented on 7.July 2010 |
| Could you please add information about the MultiBinding , especially on a column of a DataGrid
|
|
|
 |
| Rama | |
|
| Commented on 8.July 2010 |
| Very nice article. My requirement is how can I get objects for controls in DataTemplate column in code window. I added two button template column in datagrid and I want get objects of those buttons. Please assist me... Thanks
|
|
|
 |
| Rama | |
|
| Commented on 8.July 2010 |
| Very nice article. My requirement is how can I get objects for controls in DataTemplate column in code window. I added two button template column in datagrid and I want get objects of those buttons. Please assist me... Thanks
|
|
|
 |
| Tom | |
|
| Commented on 8.July 2010 |
Nice one,
How to databind a List<Customer> to Grid.
Thanks.
|
|
|
 |
| Rajni Padhiyar | |
|
| Commented on 12.July 2010 |
Nice Example
Thanks
Rajni Padhiyar
rajnicby.si@gmail.com
|
|
|
 |
| Avi | |
|
| Commented on 12.July 2010 |
| How to change the color of each row. different color for different row in WPF DataGrid ?
|
|
|
 |
| Avinash | |
|
| Commented on 12.July 2010 |
How to change the color of each row. different color for different row in WPF DataGrid ?
Invinciblemachine@gmail.com
Avinash
|
|
|
 |
| Ziddan | |
|
| Commented on 13.July 2010 |
| In Simple Words, its very Helpful, my best regards to U and Ur Efforts
|
|
|
 |
| Greg | |
|
| Commented on 21.July 2010 |
| Christian, thanks for putting this series together. It looks like you have put in a bunch of hours. I have a suggestion - you might consider putting Next Prev buttons at the bottom (but above the comments) so users can flip through your pages w/o having to scroll back to the top. Just a thought. Thanks for the effort.
|
|
|
 |
| ReV | |
|
| Commented on 24.July 2010 |
| Hi Christian, is there any way to use something like lookup-editbox for grid with same specificity!
|
|
|
 |
| Marlon Manzo | |
|
| Commented on 14.August 2010 |
| your example was very intersting and your explanation are clear, but what i need with all the HyperLink that shows in the Datagrid is try to goes to another screen on the same window, the same thing if you are working on aspx using the command "redirect"
|
|
|
 |
| Kapil | |
|
| Commented on 16.August 2010 |
| First of all I like to thanks a lot for writing this good article. I want to add button against each row of the datagrid in wpf 4.0. Can you please suggest me how can I achieve this and I also want to take the row column 0 value on that row button click. Thanks in advance.
|
|
|
 |
| Rohit Kandhal | |
|
| Commented on 17.August 2010 |
| How can i group 2 rows depending on Sex , i mean if we have male entry in row then all male should be shown together with one column showing picture of male in all rows of mail. There would be only one image of Mail.
|
|
|
 |
| Kapil | |
|
| Commented on 23.August 2010 |
How can we add footer in the data grid in framework 4.0.
Thanks & Regards
Kapil
kapilagarwal1@ymail.com
|
|
|
 |
| Majed | |
|
| Commented on 31.August 2010 |
| Well done. Thanks for this.
|
|
|
|