Click here to Skip to main content
13,143,774 members (30,715 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


11 bookmarked
Posted 26 Mar 2010

Binding a Silverlight 3 DataGrid to Dynamic Data via IDictionary (Updated)

, 26 Mar 2010
Rate this:
Please Sign up or sign in to vote.
This blog post is a bug fix (due to differences between SL2 and SL3) and expansion on my previous posts on this subject.

In this post, I demonstrate a method for binding a Silverlight 3 DataGrid to dynamic data, i.e., data which does not have properties that are known at design time. This technique results in a bound grid which is sortable and editable. This blog post is a bug fix (due to differences between SL2 and SL3) and expansion on my previous posts on this subject.

WinForms, WPF and ASP.NET are all perfectly capable of binding to dynamic data via a DataGrid, or custom TypeDescriptors. However, Silverlight has neither of these features. Around one year ago, I published a pair of articles that demonstrated a technique that could be used to bind a DataGrid to dynamic data presented as a list of dictionaries. The first article detailed how to use a ValueConverter to access the cell values within a dictionary and how a custom CollectionView could be created to permit sorting. The second article showed how to extend this solution to enable editing within the grid.

These two blog posts have proven very popular, with 84 comments between them :-). However, I have seen a recurring theme in the comments to these posts which I will now address:

  1. SL3 Sorting – I have had a number of reports that indicate sorting is broken in Silverlight 3
  2. SL3 Editing – It looks like editing is also broken in SL3 :-(
  3. Adding columns in code behind – My examples configured columns in XAML, but for truly dynamic data, this would have to be done in code-behind. A number of readers have had difficulty with converting the XAML into the required C# code.

This blog post will address these specific issues, providing a solution that works for SL3. If you are interested in the technical solution, you might want to read the first and second blog posts before you read this one. The solution for SL3 is essentially the same, it is just a few subtle differences in the DataGrid that cause these issues.

Starting with the first of the SL3 problems, sorting. The DataGrid uses the SortDescriptions property of our collection which implements ICollectionView in order to sort the data. This remains unchanged in SL3. However, the ICollectionView implementation that I presented in the previous blog post did not implement all the methods on this interface, leaving out the ones that the SL2 DataGrid does not use.

When the SL3 DataGrid performs a sort or group operation, it first calls the DeferRefresh method on ICollectionView. This is quite a neat little method; what it does is allow you to suppress the events that the collection would typically raise whilst you make a number of changes, for example, applying a sort then a grouping, then raises a single collection changed event. This results in much less work being performed by the UI as it now handles a single event rather than multiple events. You can find a good example of how this works on Matt Manela’s blog. DeferRefresh is implemented by returning an IDisposable object, the implementation is quite trivial:

public class SortableCollectionDeferRefresh : IDisposable
    private readonly SortableCollectionView _collectionView;
    internal SortableCollectionDeferRefresh(SortableCollectionView collectionView)
        _collectionView = collectionView;
    public void Dispose()
        // refresh the collection when disposed.

It is used by our collection as follows:

public class SortableCollectionView : ObservableCollection<Row>, ICollectionView
  public IDisposable DeferRefresh()
      return new SortableCollectionDeferRefresh(this);

That solves the sorting issue. :-)

The lack of editing issue was a bit odd, someone on the Silverlight forums indicated that they think this is an undocumented breaking change. With a SL3 DataGrid, if you bind to a property of type object, the column becomes read-only, even if the DataGrid itself is not read-only. The solution is simply to set the IsReadOnly of each column to false.

With these few changes, we now have a fully functioning DataGrid bound to our dynamic data:


[CodeProject does not support Silverlight content - see the above example in action on my blog.]

The final recurring question to my previous blog posts is how to create the bound DataGrid columns in code-behind. To illustrate how this is done, I will create an example where the DataGrid is bound to some XML that sits in a TextBox underneath the grid.

The example looks like this: 


[CodeProject does not support Silverlight content - see the above example in action on my blog.]

The two buttons in the centre allow you to synchronise the DataGrid and the XML, one formats the current grid contents in XML, the other takes the XML and dynamically binds the contents to the grid. You can try editing the data, then updating the XML and vice-versa. You can even add new columns to the XML data (hopefully the XML structure is pretty self explanatory – there is no error checking so take care ;-) ). The DataGrid is of course editable and sortable. 

The interesting part of the code is the method that takes the XML contents and binds it to the grid. It is as follows:

/// <summary>
/// Copies the XML contents of the textbox into the DataGrid
/// </summary>
private void XmlToGrid()
  // clear the grid
  _dataGrid.ItemsSource = null;
  // grab the xml into a XDocument
  XDocument xmlDoc = XDocument.Parse(_xmlInput.Text);
  // find the columns
  List<string> columnNames = xmlDoc.Descendants("column")
                                   .Select(a => a.Value)
  // add them to the grid
  foreach (string columnName in columnNames)
  SortableCollectionView data = new SortableCollectionView();
  // add the rows
  var rows = xmlDoc.Descendants("row");
  foreach (var row in rows)
    Row rowData = new Row();
    int index = 0;
    var cells = row.Descendants("cell");
    foreach(var cell in cells)
      rowData[columnNames[index]] = cell.Value;
  _dataGrid.ItemsSource = data;

The above code clears the grid, then uses a bit of Linq to XML to query the XML within the TextBox, creating the SortableCollectionView and Row instances which are the data objects for our dynamic data as described in the previous blog posts. The columns are created in code behind as follows:

private RowIndexConverter _rowIndexConverter = new RowIndexConverter();
private DataGridColumn CreateColumn(string property)
  return new DataGridTextColumn()
    CanUserSort = true,
    Header = property,
    SortMemberPath = property,
    IsReadOnly = false,
    Binding = new Binding("Data")
      Converter = _rowIndexConverter,
      ConverterParameter = property

This is really no different to the technique that you use when creating the column definitions in XAML. There is nothing special about XAML, it is essentially just an XML markup for creating objects.

Hopefully this blog post will help answer the recurring questions, and reduce the number of “it doesn’t work in SL3? mails I get. Perhaps I will just get 84 “Thank you” comments instead. :-)

You can download the full source code for this blog post here.

Colin E.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Colin Eberhardt
Architect Scott Logic
United Kingdom United Kingdom
I am CTO at ShinobiControls, a team of iOS developers who are carefully crafting iOS charts, grids and controls for making your applications awesome.

I am a Technical Architect for Visiblox which have developed the world's fastest WPF / Silverlight and WP7 charts.

I am also a Technical Evangelist at Scott Logic, a provider of bespoke financial software and consultancy for the retail and investment banking, stockbroking, asset management and hedge fund communities.

Visit my blog - Colin Eberhardt's Adventures in .NET.

Follow me on Twitter - @ColinEberhardt


You may also be interested in...


Comments and Discussions

QuestionThanks [modified] Pin
ebrahimasadi16-Apr-10 23:25
memberebrahimasadi16-Apr-10 23:25 
AnswerRe: Thanks Pin
Colin Eberhardt19-Apr-10 23:56
memberColin Eberhardt19-Apr-10 23:56 
GeneralRe: Thanks Pin
Ebrahim_Asadi20-Apr-10 6:42
memberEbrahim_Asadi20-Apr-10 6:42 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.170915.1 | Last Updated 27 Mar 2010
Article Copyright 2010 by Colin Eberhardt
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid