Welcome to WindowsClient.net | Sign in | Join

WPF Toolkit: DataGrid Feature Walkthrough

The Build System

The WPF team is excited to release version 1 of our new WPF DataGrid control starting on Monday, October 27, 2008! Binaries and source code for the DataGrid can be downloaded from Codeplex.

Feature Walkthrough

Version 1 of the WPF DataGrid includes many of the features which Line-of-Business (LOB) application authors need to create rich end-user experiences for viewing and editing data. Features such as autogeneration of columns, a variety of stock column types, and built-in functionality like editing, sorting, and keyboard navigation will help developers get their data-centric applications up and running quickly. Developers can also create unique, branded experiences using DataGrid’s variety of styling features and advanced options such as row details and row-level validation. Following is a walkthrough of the major DataGrid features and explanations of how to use these features in your application.

Toolkit Screenshot

Autogeneration of Columns

With only one line of code, it’s possible to generate a fully-functioning DataGrid. This is due to the autogeneration feature which will automatically map each field of the data source to a stock column type (DataGridTextBoxColumn, DataGridCheckBoxColumn, DataGridComboBoxColumn, or DataGridHyperlinkColumn). Autogeneration is on by default, so simply setting an ItemsSource and running the application with generate columns and produce a working DataGrid with features such as sorting, editing, keyboard navigation, end-user row and column resizing, and end-user column reordering through drag and drop.

    <dg:DataGrid ItemsSource="{StaticResource myData}"/>
    

Column Types

The DataGrid includes four basic stock column types:

  • DataGridTextBoxColumn
  • DataGridCheckBoxColumn
  • DataGridComboBoxColumn
  • DataGridHyperlinkColumn

Any of these column types can be specified in the DataGrid’s Columns collection. Stock columns include a variety properties which allow developers to customize the column’s look and behavior such as Header (to specify header content), Binding (to specify the data field the column should bind to), Width (can be an absolute value or one of the auto-sizing values, including Auto, SizeToHeader, SizeToCells, or *), CanUserSort (to toggle the ability to sort the column), and IsReadOnly (to toggle the ability to edit the column).

    <dg:DataGrid ItemsSource="{StaticResource myData}"/> >
    <dg:DataGrid.Columns>
        <dg:DataGridTextColumn Header="No." Width="SizeToCells"  
                                           Binding="{Binding CheckNumber}" 
                                           IsReadOnly="True"/>
        <dg:DataGridTextColumn Header="Date" 
                                           Binding="{Binding Date, StringFormat=d}" />
        <dg:DataGridTextColumn Header="Pay To" MinWidth="200" 
                                           Binding="{Binding Recipient}"
                                           CanUserSort="False" />
    </dg:DataGrid.Columns>
    </dg:DataGrid>
    

A fifth column type, DataGridTemplateColumn, was provided as a convenient way to create a new column type. Developers can set any WPF control in the CellTemplate of the DataGridTemplateColumn to create a custom column type. If the control in the CellTemplate does not have a built-in editing template (such as a Button) or the developer would like to use a different editing template, the developer can also specify a CellEditingTemplate to define what template the column should use when in editing mode (for example, TextBox). In the following example, a date column is created using the new DatePicker control as the CellEditingTemplate:

    <dg:DataGridTemplateColumn Header="Date" MinWidth="100">
        <dg:DataGridTemplateColumn.CellEditingTemplate>
            <DataTemplate>
                <dg:DatePicker SelectedDate="{Binding Date}" SelectedDateFormat="Short" />
            </DataTemplate>
        </dg:DataGridTemplateColumn.CellEditingTemplate>
        <dg:DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Date, StringFormat=d}" />
            </DataTemplate>
        </dg:DataGridTemplateColumn.CellTemplate>
    </dg:DataGridTemplateColumn>
    
Toolkit Screenshot

Selection

DataGrid has built-in support for a variety of selection modes and units. The SelectionMode property can be set to Cell (for cell selection only), Row (for full row selection only), or CellOrRowHeader (where users can click on cells for cell selection or row headers to select full rows). The SelectionUnit property can be set to Single or Extended mode to allow for single selection or selection of multiple rows/cells.

Row Details

DataGrid’s row details feature allows application authors to specify a template for showing additional fields or other information in an expanded section of the row. This feature is useful, for example, if the data source has many fields which the developer doesn’t want to display as columns, or if there is a form which should be associated with each row. Developers can define any DataTemplate to be used as the RowDetailsTemplate and can set the RowDetailsVisibilityMode to Visible, Collapsed, or VisibleWhenSelected (where the row details are only visible if the row is selected). In the following example, a row details template is specified which allows the user to choose a category with a ComboBox.

    <dg:DataGrid x:Name="dg" ItemsSource="{Binding}" 
            RowDetailsVisibilityMode="VisibleWhenSelected">

        <dg:DataGrid.RowDetailsTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal" Margin="20,0,0,0">
                    <TextBlock Text="Category:" FontWeight="Bold"/>
                    <ComboBox IsEditable="True" 
                              ItemsSource="{Binding Source={x:Static Data:CheckBook.Categories}}" 
                             Text="{Binding Category}" />
                 </StackPanel>
            </DataTemplate>
        </dg:DataGrid.RowDetailsTemplate> 
    
Toolkit Screenshot

Validation

Both cell- and row-level validation are possible in the WPF DataGrid. Since .NET 3.5, cell validation has been able to be achieved using IDataErrorInfo on any Binding. New in .NET 3.5 SP1 is a feature called BindingGroup which enables cross-field validation. In DataGrid, this feature is used to enable row-level validation where different cells of the DataGrid can be validated against each other. Developers can specify a collection of RowValidationRules which are used to validate the rows in the DataGrid and can define a RowValidationErrorTemplate to determine the visual style of the notification which the end-user receives when there is a validation error.

Row & Column Headers

DataGrid’s headers can be customized in a variety of ways to create the optimal DataGrid experience for every application. DataGrid’s HeadersVisibility property can be set to Row, Column, All, or None to toggle the visibility of the row and column headers. Developers can also set the RowHeaderWidth and ColumnHeaderHeight to change the size of headers. Row and column headers can also be styled through the RowHeaderStyle, RowHeaderTemplate, ColumnHeaderStyle, and ColumnHeaderTemplate properties. Some examples of styled headers are below:

Toolkit Screenshot

Styling Properties

In addition to the header styling properties, DataGrid also includes many other properties which can be used to customize the DataGrid’s look and feel. The Background and AlternatingRowBackground properties can be used to set alternating row colors to enhance readability. Gridlines can be customized using GridLinesVisibility, HorizontalGridLinesBrush, and VerticalGridLinesBrush. Cells and rows can also be assigned styles using CellStyle and RowStyle.

Design Time

The DataGrid has a design time experience for both Expression Blend and the Visual Studio WPF Designer. Once the DataGrid has an ItemsSource assigned, the DataGrid designer will allow you to edit DataGrid properties, modify the Columns collection by adding and removing columns, and edit the properties of each column.

Get Started with DataGrid

Version 1 of the WPF DataGrid includes all of the above features and more. Check out the DataGrid in the WPF Toolkit on CodePlex starting October 28th!

Comments: 27

You must Login to comment.
 

Mike_BB: On October 29, 2008 9:21 AM said:

mistakes

<DataTemplate>

               <dg:DatePicker SelectedDate="{Binding Date}" SelectedDateFormat="Short" />

           </DataTemplate>

in this case date show, but don't modified!

Right code

<dg:DatePicker SelectedDate="{Binding Path=Date, Mode=TwoWay}" SelectedDateFormat="Short" />

 
 

vader1982: On November 5, 2008 3:07 PM said:

Hi,

I tried to change the ColumnHeader in my DataGrid. - without success - :-(

How can I change the "HorizontalAlignment" Property from the ColumnHeader.

I didn't find the "ColumnHeaderTemplate" to change the Template.

I need a little bit help.

Many thanks in advance.

 
 

seani: On November 7, 2008 6:20 AM said:

Hi,

Thanks for the WPF toolkit first and foremost. Nice to see a grid out there :)

My question is: Is there a built-in way to save and restore the column order/sizes/sortorders (basically the layout)?

Thanks!

Sean

 
 

vinsibal: On November 7, 2008 8:39 AM said:

For DataGrid related questions please use the discussion list on codeplex, www.codeplex.com/.../List.aspx.

 
 

RicheRich: On December 1, 2008 9:12 PM said:

Thanks also for the toolkit.

Is the personal finance manager sample shown above available for download?

 
 

Riccardo63: On December 23, 2008 12:13 PM said:

There is an important feature that we're waiting : the filter capabilities. Do you think to that datagrid will have it ? If yes, when? Thank you !

 
 

ninja243: On January 5, 2009 9:27 AM said:

@RicheRich: Yes the sample is available follow this link:   windowsclient.net/.../entry76491.aspx

 
 

sreejithrajan: On January 9, 2009 1:05 AM said:

Hi,

How to change the color of selected row in datagrid

 
 

Iliya Tretyakov: On January 13, 2009 10:21 AM said:

Can I hide empty line in the bottom of DataGrid?

 
 

Riccardo63: On January 14, 2009 12:21 PM said:

Any suggestion about filtering capabilities?

 
 

tarb: On January 15, 2009 10:58 AM said:

Am I correct in understanding that the DatePicker released with the October 2008 WPF Toolkit and used in sample code above should not be deployed due to a memory leak?

If so, can you recommend an alternative?

 
 

Samantha-Msft: On February 11, 2009 7:15 PM said:

Riccardo63 - Like other ItemsControls, Filtering is available in DataGrid through the CollectionView.  

 
 

Samantha-Msft: On February 11, 2009 7:19 PM said:

sreejithrajan, you can change the color of the selected row using the RowStyle property.  In the RowStyle, you'll want to define a Trigger which changes the Background property when IsSelected is true.  This blog post covers many DataGrid styling scenarios: blogs.msdn.com/.../styling-microsoft-s-wpf-datagrid.aspx

 
 

Samantha-Msft: On February 11, 2009 7:22 PM said:

Iliya Tretyakov - Please see this thread: www.codeplex.com/.../View.aspx

 
 

Samantha-Msft: On February 11, 2009 7:24 PM said:

tarb - Yes, the DatePicker from the October 2008 release should not be deployed due to a memory leak.  However, we have released an update (January 2009) which fixes this issue, so as long as you use the latest DatePicker, you shouldn't have a problem.  You can get the new release here: www.codeplex.com/.../ProjectReleases.aspx

 
 

Samantha-Msft: On February 11, 2009 7:25 PM said:

Mike_BB, thanks for reporting this.  It is a known issue and will be fixed in an upcoming release.

 
 

Samantha-Msft: On February 11, 2009 7:27 PM said:

vader1982, you should be able to use ColumnHeaderStyle to change the HorizontalAlignment, or if you prefer to change the template you can retemplate DataGridColumnHeader.  Please check out this blog post for information about common DataGrid styling questions: blogs.msdn.com/.../styling-microsoft-s-wpf-datagrid.aspx

 
 

Samantha-Msft: On February 11, 2009 7:29 PM said:

seani, I don't think there is a way to save the layout built in.  You'd have to do some serialization to save that information.  You can find more information about serialization on MSDN here: msdn.microsoft.com/.../ms750605.aspx

 
 

Samantha-Msft: On February 11, 2009 7:33 PM said:

To All Posters:

Please leave comments and questions on the Codeplex Discussion forums at www.codeplex.com/.../List.aspx.  

The Codeplex forums are watched daily by members of the WPF platform team who can help to answer your questions.  It is a great resource to search when you come across an issue, since many developers have asked similar questions and reported the same bugs.  

This feedback page is not checked as often as the Codeplex site, so if you are looking for a timely response to your inquiry, Codeplex is your best bet.

Thanks!

Samantha

 
 

stevensrf2: On February 21, 2009 11:23 PM said:

Anyone have any source code and project available for download that uses the datagrid?

I especially would be interested in the code that produces the datagrid shown on this webpage. Anyone know where I may download that code. Is filtering possible on this grid

 
 

elixir67: On March 7, 2009 12:41 PM said:

How can we implement a treelistview using the new DataGrid? I mean a tree with multi-column.

There's one sample in MSDN using treeview. But except the tree the DataGrid is more suitable for me. Multiple Select, Editable cell all can save me a lot of time.

Anyone has the idea or code? Thanks very much.

 
 

bradutz01: On March 19, 2009 9:15 AM said:

Hi, Whta is the name space for primitives?

 
 

atmaraam: On March 30, 2009 3:52 PM said:

hi..

is it possible to bind the new version of datagrid to a self referencing table using hierarchical data source?

 
 

sreejithrajan: On April 6, 2009 7:18 AM said:

WPF datagrid cells are made editable on click of edit button in respective datagrid row.

upon editable, once the user leaves the grid cell,wpf datagrid cells turns readonly . I want to avoid the datagrid cells turning readonly upon user leaves that specific grid cell.

 
 

MemphiZ: On April 29, 2009 5:22 AM said:

Could someone please post the DataGridHeaderBrush for the green Header like in the Screenshot up there? i cant find it in the manual...

 
1 2 Next >

Featured Item

Microsoft Communities