Skip to content

WPF Toolkit DataGrid, Part I – Introduction

by Samuel Moura on April 15th, 2009

Recently I had to recreate in WPF a Windows Forms panel that used DevExpress XtraGrid to present data in tabular form, keeping the same look and feel as it was part of an existing application. I Googled around to find out what different solutions exist out there for presenting data this way in WPF. After searching for a while and looking at solutions I found a few interesting ones:

I ended up using WPF Toolkit. The main reasons were: WPF Toolkit is free, open source and it was the one that allowed me greater flexibility. In this series of articles I intend to present you with all the functionality I managed to implement on my UserControl. For obvious reasons I will not disclose the code developed within our project but will provide working samples of the most relevant achievements in detail using a sample application.

To access WPF Toolkit’s DataGrid start by downloading and installing the latest release on your PC. You can download it from the link provided here.

Roadmap

In this article we will go through the following topics:

  • Hands on your First WPF DataGrid
  • DataGridColumn Hierarchy
  • Using DataGridColumns to enhance the DataGrid sample

Hands on your first WPF DataGrid

After installing WPF Toolkit we can start by creating a new WPF Application within Visual Studio and add the WPF Toolkit reference on it, which can be accessed through the ‘Add Reference’ .Net tab.

I believe that going through a live sample is the best way to adopt a new technology and as so we will dive directly into using the code instead of first going through a bunch of theory and only afterwards peaking on some code. Adding a DataGrid to a WPF application can be done quite easily:

<UserControl x:Class="SampleWpfDataGrid.PeopleView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:WpfToolkit="http://schemas.microsoft.com/wpf/2008/toolkit">
    <WpfToolkit:DataGrid
        ItemsSource="{Binding Path=PlayerAges}"
        HorizontalScrollBarVisibility="Hidden" SelectionMode="Extended">
    </WpfToolkit:DataGrid>
</UserControl>

We just need to instantiate a DataGrid object from the WPF Toolkit and bind it to a collection in order to display its data. In this example we use the AutoGenerateColumns feature of the DataGrid to generate the columns so that all the information in PlayerAges gets correctly displayed – note that this is enabled by default.

WpfToolkitDataGrid-ss001

Basically what you see are two teams of people each containing 5 members. The grid will display a series of data regarding each team member’s age and its deviation towards the team players average age.

In the sample application I have separated the logic from the view in a way that the MVVM pattern can easily be used by specifying a DataTemplate for the ViewModel. There is a class which represents the ViewModel – TeamModel – and it contains a list of PlayerAge entries. Each row in the DataGrid represents a PlayerAge.  I then use a special row to represent the Team that I can use in conjunction with the IsExpanded plus IsSubItem properties to group the items on the list by teams. The DataGrid is added to the PeopleView UserControl that is used on the SampleWindow.

For now you can download a working sample of what you have seen so far from this link.

This is a straight forward example on how to use the WPF Toolkit’s DataGrid. It shows you how easy it is for you to present data and allow users to edit it. Obviously this alone is not of much use because you will want to style your grid and give it a set of behaviors according to whatever state your application is in. We will look on how to customize and give this DataGrid a nice look and feel along with some additional functionality.

DataGridColumn Hierarchy

Before going on with our sample lets have a look on how the WPF Toolkit DataGrid is structured in regard to the default columns types provided.

WpfToolkitDataGrid-ss002

We have a DataGrid class to which we bind a data source and then use the DataGridColumn’s to specify how the data will be presented for each field according to that field’s type. There are several types of DataGridColumns available: DataGridHyperLinkColumn, DataGridCheckBoxColumn, DataGridTextColumn, DataGridComboBoxColumn and DataGridTemplateColumn. Most of these column types are self explanatory, we have columns for text, check boxes, etc. The Template Column is perhaps the one that may not be so clear, it is a column that can be used in conjunction with ControlTemplates to create whatever type of column you require, being it a Chart, a user control, etc.

Using DataGridColumns to enhance the DataGrid sample

Lets pick up our DataGrid sample project and create columns for all the fields we want to present. Since some fields will only be used for logic you must hide all other from the user. Only IsEnabled, Name, Age, Deviation, Category and DeviationPercentage fields will be visible.

The first thing you have to do so that you can control what columns are displayed is to set the AutoGenerateColumns to false on the DataGrid. Afterwards you can start adding columns and binding them to their corresponding fields. This is an example on how you can define your columns:

<WpfToolkit:DataGrid
    ItemsSource="{Binding Path=PlayerAges}"
    HorizontalScrollBarVisibility="Hidden" SelectionMode="Extended"
    CanUserAddRows="False" CanUserDeleteRows="False"
    CanUserResizeRows="False" CanUserSortColumns="False"
    AutoGenerateColumns="False"
    RowHeaderWidth="17" RowHeight="25">
    <WpfToolkit:DataGrid.Columns>
        <WpfToolkit:DataGridCheckBoxColumn
            Header="Enabled" Width=".5*"
            Binding="{Binding Path=IsEnabled}"/>
        <WpfToolkit:DataGridTextColumn
            Header="Player Name" Width="2*"
            Binding="{Binding Path=Name}"/>
        <WpfToolkit:DataGridTextColumn
            Header="Age" Width="1*"
            Binding="{Binding Path=Age}"/>
        <WpfToolkit:DataGridTextColumn
            Header="Deviation" Width="1*"
            Binding="{Binding Path=Deviation}"/>
        <WpfToolkit:DataGridComboBoxColumn
            Header="Category" Width="1*"
            ItemsSource="{StaticResource Categories}"
            SelectedValueBinding="{Binding Path=Category}"
            TextBinding="{Binding Path=Category}" />
        <WpfToolkit:DataGridTextColumn
            Header="Deviation Chart" Width="1*"
            Binding="{Binding Path=DeviationPercentage}"/>
    </WpfToolkit:DataGrid.Columns>
</WpfToolkit:DataGrid>

Notice that you started by tweaking a bit the DataGrid to conform with some of the required features. You have disabled a series of functionality mainly because there is no need to handle new rows input. Sorting does not make sense has groups are being used, etc – most of it is intuitively understandable. Notice that AutoGenerateColumns was set to false and that RowHeight was set to 25 so that when the user is picking something from the category combo box the row does not need to grow to allow the layout of the control – if you wish, just remove this value from the DataGrid and watch how picking something from the Category combo box now looks.

You have added a DataGridCheckBoxColumn and linked it to our IsEnabled field. Added a series of DataGridTextColumns binding them to Name, Age and Deviation along with a DataGridComboBoxColumn to bind to the player’s category. Finally, for now, notice how the Deviation Chart column was set to a DataGridTextColumn, this will be replaced by a DataGridTemplateColumn in the future when we get into styling the DataGrid.

Each column has been given a Header name and a Width according to star notation (as in WPF Grid control). Has you can see from the code, the Name column should be twice as large as, for instance, the Age column. This allows us to create user friendly layouts for our columns without too much effort. This is how the sample application is currently looking:

WpfToolkitDataGrid-ss004

To see a working sample of this new layout please download this file.

End of Part I

You have given the first steps in understanding how to use the WPF Toolkit’s DataGrid in an application. You are now able to create simple DataGrids and specify columns to better control how your data gets presented to the user.

Much is there to find out about the WPF Toolkit DataGrid. Stay tuned for future blog posts has I will go through more complex features including a complete restyling of the DataGrid.

From → WPF

34 Comments
  1. Hello permalink

    Thank you so much wonderful article
    I was looking for one property…..you saved me!!

  2. Your site is awesome!

    I also found this one which might help you all.

    Best implementation of wpf extended datagrid can be found here WPF Extended DataGrid

    Project Description

    This is extended version of WPF toolkit DataGrid control.

    This grid has features like

    1:Column Choosers.
    2:AutoFilter Control.
    3:Export To Excel Feature.
    4:Copy Paste To Excel and Copy Paste From Excel 5:To DataGrid.
    6:Three State Sorting.
    7:Displaying Sort Order If Multiple Sort is done

  3. Shai permalink

    I have used as WpfToolkit-DataGrid as stated above.
    But some reason I have to click three times to select a check box.
    on first click, it select row
    on second click, it select cell
    finally on third click it select the check box.

    Can you tell me how do i fix this issue?

    Thank you

  4. Hugo permalink

    Hi Samuel,

    I would like to get some insight into how I can only only choose a part of the styles that you have defined, and only define what is needed in xaml.

    Do you think it is a good idea of having a lot xaml-code, dealing with layout ? What do you think of the readability of the xaml-code specifically ? Is it a good idea to offer code-behind versions of every example ?
    Or build an own assembly, that exposes methods to change the layout in code-behind ?
    This would go against the MVVM pattern, how good/bad to you think it is ?

    I only want to change the cell border and cell background, and an alternating row background of this datagrid.

    I guess it would be good practice not to exposes code that I don’t need to know of, but use an assembly instead and just call methods that do the things above.

  5. Hugo permalink

    Can I post files too ?

  6. Keith ONeill permalink

    Samuel,

    Thanks for the great series on the DataGrid control. I’ve found myself referring to it a lot. I was wondering if you have a PayPaly link for me to donate or an Amazon wish list I can get you something from?

    Thanks again,
    Keith

  7. joeSydneyAu permalink

    Did you ever write Part V of the series, as promised at the end of Part IV? i cannot find it.

    By the way, your contact email page is not working, it says:

    Failed to send your message. Please try later or contact administrator by other way.

  8. Jack permalink

    Hi Samuel,

    I new relatively new to WPF, and have read some chapters of books and have studied you code. Im particularly interested in your response/help with regards to adding the facility to change the TeamModel.Categories property to a modifyable ObservableCollection so the user can enter ‘new’ strings into the comboboxes and have the list updated. I’ve got it working, BUT when i go to sort the ObservableCollection, the previously entered combobox values in the grid disappear. Can you suggest as to why? Is the binding lost due to the source being sorted and is there a way so the Categories remain?

    Jack.

  9. @Kshitij As a starting point for WPF I would recommend:

    I only did preliminary tests with DevExpress grid, it did not meet the requirements I needed for what I was developing at the time so I sticked with the WPF datagrid.

  10. Kshitij permalink

    @Samuel Moura
    Samuel,

    I really appreciate your time and response.

    We are midway on a project and this next module could require ASP.Net GridView like functionality.

    But as you said, we will have invest some time as team to get up to speed with WPF.

    It seems like I am jumping on WPF pretty late and now there is so many resources to look at and choose from.

    Would you point me to at good starting resources?

    Did you have favorable opinion of the DevExpress Grid?

Trackbacks & Pingbacks

  1. In Pursuit of Higher Learning « Me and My Fabulous Little Adventures
  2. Wochenend-Geblubber KW21/09 | Biggle's Blog
  3. 9eFish
  4. DotNetShoutout

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS