<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Colin Eberhardt&#039;s Adventures in .NET &#187; DataGrid</title>
	<atom:link href="http://www.scottlogic.co.uk/blog/colin/tag/datagrid/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.scottlogic.co.uk/blog/colin</link>
	<description>Colin Eberhardt&#039;s Adventures in .NET</description>
	<lastBuildDate>Thu, 09 Feb 2012 10:21:18 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Binding a Silverlight 3 DataGrid to dynamic data via IDictionary (Updated)</title>
		<link>http://www.scottlogic.co.uk/blog/colin/2010/03/binding-a-silverlight-3-datagrid-to-dynamic-data-via-idictionary-updated/</link>
		<comments>http://www.scottlogic.co.uk/blog/colin/2010/03/binding-a-silverlight-3-datagrid-to-dynamic-data-via-idictionary-updated/#comments</comments>
		<pubDate>Fri, 26 Mar 2010 15:02:28 +0000</pubDate>
		<dc:creator>Colin Eberhardt</dc:creator>
				<category><![CDATA[codeproject]]></category>
		<category><![CDATA[binding]]></category>
		<category><![CDATA[DataGrid]]></category>
		<category><![CDATA[silverlight]]></category>

		<guid isPermaLink="false">http://www.scottlogic.co.uk/blog/colin/?p=611</guid>
		<description><![CDATA[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) [...]]]></description>
			<content:encoded><![CDATA[
<div class="topsy_widget_data topsy_theme_light-green" style="float: right;margin-left: 0.75em; background: url(data:,%7B%20%22url%22%3A%20%22http%253A%252F%252Fwww.scottlogic.co.uk%252Fblog%252Fcolin%252F2010%252F03%252Fbinding-a-silverlight-3-datagrid-to-dynamic-data-via-idictionary-updated%252F%22%2C%20%22style%22%3A%20%22big%22%2C%20%22title%22%3A%20%22Binding%20a%20Silverlight%203%20DataGrid%20to%20dynamic%20data%20via%20IDictionary%20%28Updated%29%20%23%22%20%7D);"></div>
<p><em>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.</em></p>
<p>WinForms, WPF and ASP.NET are all perfectly capable of binding to dynamic data via a DataGrid, or custom <a href="http://msdn.microsoft.com/en-us/library/ms171819.aspx">TypeDescriptors</a>. 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 <a href="http://www.scottlogic.co.uk/blog/colin/2009/04/binding-a-silverlight-datagrid-to-dynamic-data-via-idictionary/">first article</a> 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 <a href="http://www.scottlogic.co.uk/blog/colin/2009/04/binding-a-silverlight-datagrid-to-dynamic-data-part-2-editable-data-and-inotifypropertychanged/">second article</a> showed how to extend this solution to enable editing within the grid.</p>
<p>These two blog posts have proven very popular, with <strong>84 comments</strong> between them <img src='http://www.scottlogic.co.uk/blog/colin/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> . However I have seen a recurring theme in the comments to these posts which I will now address:</p>
<ol>
<li><strong>SL3 Sorting</strong> &#8211; I have had a number of reports that indicate sorting is broken in Silverlight 3</li>
<li><strong>SL3 Editing</strong> &#8211; It looks like editing is also broken in SL3 <img src='http://www.scottlogic.co.uk/blog/colin/wp-includes/images/smilies/icon_sad.gif' alt=':-(' class='wp-smiley' /> </li>
<li><strong>Adding columns in code behind</strong> &#8211; 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.</li>
</ol>
<p>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 <a href="http://www.scottlogic.co.uk/blog/colin/2009/04/binding-a-silverlight-datagrid-to-dynamic-data-via-idictionary">first</a> and <a href="http://www.scottlogic.co.uk/blog/colin/2009/04/binding-a-silverlight-datagrid-to-dynamic-data-part-2-editable-data-and-inotifypropertychanged/">second</a> 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.</p>
<p>Starting with the first of the SL3 problems, sorting. The DataGrid uses the SortDescriptions property of our collection which implements <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.icollectionview%28VS.95%29.aspx">ICollectionView</a>  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. </p>
<p>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 <a href="http://blogs.msdn.com/matt/archive/2008/08/28/collectionview-deferrefresh-my-new-best-friend.aspx">Matt Manela&#8217;s blog</a>. DeferRefresh is implemented by returning in IDisposable object, the implementation is quite trivial:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> SortableCollectionDeferRefresh <span style="color: #008000;">:</span> IDisposable
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #0600FF; font-weight: bold;">readonly</span> SortableCollectionView _collectionView<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">internal</span> SortableCollectionDeferRefresh<span style="color: #008000;">&#40;</span>SortableCollectionView collectionView<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        _collectionView <span style="color: #008000;">=</span> collectionView<span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">void</span> Dispose<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #008080; font-style: italic;">// refresh the collection when disposed.</span>
        _collectionView<span style="color: #008000;">.</span><span style="color: #0000FF;">Refresh</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>It is used by our collection as follows:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> SortableCollectionView <span style="color: #008000;">:</span> ObservableCollection<span style="color: #008000;">&lt;</span>Row<span style="color: #008000;">&gt;</span>, ICollectionView
<span style="color: #008000;">&#123;</span>
  <span style="color: #008000;">...</span>
  <span style="color: #0600FF; font-weight: bold;">public</span> IDisposable DeferRefresh<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
  <span style="color: #008000;">&#123;</span>
      <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #008000;">new</span> SortableCollectionDeferRefresh<span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
  <span style="color: #008000;">&#125;</span>
  <span style="color: #008000;">...</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>That solves the sorting issue <img src='http://www.scottlogic.co.uk/blog/colin/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>The lack of editing issue was a but odd, someone on the Silverlight forums indicated that they think this is an <a href="http://forums.silverlight.net/forums/p/113143/254948.aspx">undocumented breaking change</a>. 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.</p>
<p>With these few changes we now how a fully functioning DataGrid bound to our dynamic data:</p>
<div id="slPluginHost1" > <object id="SilverlightPlugin1" width="300" height="300" data="data:application/x-silverlight," type="application/x-silverlight-2" ><param name="source" value="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2010/03/SilverlightTable.xap"/><a href="http://go.microsoft.com/fwlink/?LinkID=124807"  style="text-decoration: none;"> <img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style: none"/></a></object></div>
<p>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.</p>
<p>The example looks like this:</p>
<div id="slPluginHost2" > <object id="SilverlightPlugin2" width="300" height="470" data="data:application/x-silverlight," type="application/x-silverlight-2" ><param name="source" value="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2010/03/SilverlightTable2.xap"/><a href="http://go.microsoft.com/fwlink/?LinkID=124807"  style="text-decoration: none;"> <img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style: none"/></a></object></div>
<p>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 &#8211; there is no error checking so take care <img src='http://www.scottlogic.co.uk/blog/colin/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> ). The DataGrid is of course editable and sortable.</p>
<p>The interesting part of the code is the method that takes the XML contents and binds it to the grid. It is as follows:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
<span style="color: #008080; font-style: italic;">/// Copies the XML contents of the textbox into the DataGrid</span>
<span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
<span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">void</span> XmlToGrid<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
  <span style="color: #008080; font-style: italic;">// clear the grid</span>
  _dataGrid<span style="color: #008000;">.</span><span style="color: #0000FF;">ItemsSource</span> <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">;</span>
  _dataGrid<span style="color: #008000;">.</span><span style="color: #0000FF;">Columns</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Clear</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
  <span style="color: #008080; font-style: italic;">// grab the xml into a XDocument</span>
  XDocument xmlDoc <span style="color: #008000;">=</span> XDocument<span style="color: #008000;">.</span><span style="color: #0000FF;">Parse</span><span style="color: #008000;">&#40;</span>_xmlInput<span style="color: #008000;">.</span><span style="color: #0000FF;">Text</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
  <span style="color: #008080; font-style: italic;">// find the columns</span>
  List<span style="color: #008000;">&lt;</span><span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&gt;</span> columnNames <span style="color: #008000;">=</span> xmlDoc<span style="color: #008000;">.</span><span style="color: #0000FF;">Descendants</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;column&quot;</span><span style="color: #008000;">&#41;</span>
                                   <span style="color: #008000;">.</span><span style="color: #0000FF;">Attributes</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;name&quot;</span><span style="color: #008000;">&#41;</span>
                                   <span style="color: #008000;">.</span><span style="color: #0600FF; font-weight: bold;">Select</span><span style="color: #008000;">&#40;</span>a <span style="color: #008000;">=&gt;</span> a<span style="color: #008000;">.</span><span style="color: #0000FF;">Value</span><span style="color: #008000;">&#41;</span>
                                   <span style="color: #008000;">.</span><span style="color: #0000FF;">ToList</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
  <span style="color: #008080; font-style: italic;">// add them to the grid</span>
  <span style="color: #0600FF; font-weight: bold;">foreach</span> <span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span> columnName <span style="color: #0600FF; font-weight: bold;">in</span> columnNames<span style="color: #008000;">&#41;</span>
  <span style="color: #008000;">&#123;</span>
    _dataGrid<span style="color: #008000;">.</span><span style="color: #0000FF;">Columns</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Add</span><span style="color: #008000;">&#40;</span>CreateColumn<span style="color: #008000;">&#40;</span>columnName<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
  <span style="color: #008000;">&#125;</span>
&nbsp;
  SortableCollectionView data <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> SortableCollectionView<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
  <span style="color: #008080; font-style: italic;">// add the rows</span>
  var rows <span style="color: #008000;">=</span> xmlDoc<span style="color: #008000;">.</span><span style="color: #0000FF;">Descendants</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;row&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
  <span style="color: #0600FF; font-weight: bold;">foreach</span> <span style="color: #008000;">&#40;</span>var row <span style="color: #0600FF; font-weight: bold;">in</span> rows<span style="color: #008000;">&#41;</span>
  <span style="color: #008000;">&#123;</span>
    Row rowData <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Row<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #6666cc; font-weight: bold;">int</span> index <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
    var cells <span style="color: #008000;">=</span> row<span style="color: #008000;">.</span><span style="color: #0000FF;">Descendants</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;cell&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #0600FF; font-weight: bold;">foreach</span><span style="color: #008000;">&#40;</span>var cell <span style="color: #0600FF; font-weight: bold;">in</span> cells<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
      rowData<span style="color: #008000;">&#91;</span>columnNames<span style="color: #008000;">&#91;</span>index<span style="color: #008000;">&#93;</span><span style="color: #008000;">&#93;</span> <span style="color: #008000;">=</span> cell<span style="color: #008000;">.</span><span style="color: #0000FF;">Value</span><span style="color: #008000;">;</span>
      index<span style="color: #008000;">++;</span>
    <span style="color: #008000;">&#125;</span>
    data<span style="color: #008000;">.</span><span style="color: #0000FF;">Add</span><span style="color: #008000;">&#40;</span>rowData<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
  <span style="color: #008000;">&#125;</span>
&nbsp;
  _dataGrid<span style="color: #008000;">.</span><span style="color: #0000FF;">ItemsSource</span> <span style="color: #008000;">=</span> data<span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>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:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">private</span> RowIndexConverter _rowIndexConverter <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> RowIndexConverter<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">private</span> DataGridColumn CreateColumn<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span> property<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
  <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #008000;">new</span> DataGridTextColumn<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
  <span style="color: #008000;">&#123;</span>
    CanUserSort <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">true</span>,
    Header <span style="color: #008000;">=</span> property,
    SortMemberPath <span style="color: #008000;">=</span> property,
    IsReadOnly <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">false</span>,
    Binding <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Binding<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Data&quot;</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
      Converter <span style="color: #008000;">=</span> _rowIndexConverter,
      ConverterParameter <span style="color: #008000;">=</span> property
    <span style="color: #008000;">&#125;</span>
  <span style="color: #008000;">&#125;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>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.</p>
<p>Hopefully this blog post will help answer the recurring questions, and reduce the number of &#8220;it doesn&#8217;t work in SL3&#8243; mails I get. Perhaps I will just get 84 &#8220;Thank you&#8221; comments instead <img src='http://www.scottlogic.co.uk/blog/colin/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>You can download the full sourcecode for this blog post: <a href='http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2010/03/SilverlightTable.zip'>SilverlightTable.zip</a></p>
<p>Regards, Colin E.</p>

]]></content:encoded>
			<wfw:commentRss>http://www.scottlogic.co.uk/blog/colin/2010/03/binding-a-silverlight-3-datagrid-to-dynamic-data-via-idictionary-updated/feed/</wfw:commentRss>
		<slash:comments>32</slash:comments>
		</item>
		<item>
		<title>Binding a Silverlight DataGrid to dynamic data Part 2 &#8211; editable data and INotifyPropertyChanged</title>
		<link>http://www.scottlogic.co.uk/blog/colin/2009/04/binding-a-silverlight-datagrid-to-dynamic-data-part-2-editable-data-and-inotifypropertychanged/</link>
		<comments>http://www.scottlogic.co.uk/blog/colin/2009/04/binding-a-silverlight-datagrid-to-dynamic-data-part-2-editable-data-and-inotifypropertychanged/#comments</comments>
		<pubDate>Wed, 22 Apr 2009 13:42:32 +0000</pubDate>
		<dc:creator>Colin Eberhardt</dc:creator>
				<category><![CDATA[codeproject]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[binding]]></category>
		<category><![CDATA[DataGrid]]></category>
		<category><![CDATA[silverlight]]></category>

		<guid isPermaLink="false">http://www.scottlogic.co.uk/blog/colin/?p=275</guid>
		<description><![CDATA[UPDATE: This blog post was written with a SL2 DataGrid, for SL3, please see my updated blog post. In my previous blog post I described a method for solving the commonly faced problem of binding a Silverlight DataGrid to dynamic data, the form of which is not know at compile time. This blog post extends [...]]]></description>
			<content:encoded><![CDATA[
<div class="topsy_widget_data topsy_theme_light-green" style="float: right;margin-left: 0.75em; background: url(data:,%7B%20%22url%22%3A%20%22http%253A%252F%252Fwww.scottlogic.co.uk%252Fblog%252Fcolin%252F2009%252F04%252Fbinding-a-silverlight-datagrid-to-dynamic-data-part-2-editable-data-and-inotifypropertychanged%252F%22%2C%20%22style%22%3A%20%22big%22%2C%20%22title%22%3A%20%22Binding%20a%20Silverlight%20DataGrid%20to%20dynamic%20data%20Part%202%20-%20editable%20data%20and%20INotifyPropertyChanged%20%23%22%20%7D);"></div>
<p><strong>UPDATE</strong>: This blog post was written with a SL2 DataGrid, for SL3, please see my <a href="http://www.scottlogic.co.uk/blog/colin/2010/03/binding-a-silverlight-3-datagrid-to-dynamic-data-via-idictionary-updated/">updated blog post</a>.</p>
<p>In my <a href="http://www.scottlogic.co.uk/blog/colin/2009/04/binding-a-silverlight-datagrid-to-dynamic-data-via-idictionary/">previous blog post</a> I described a method for solving the commonly faced problem of binding a Silverlight DataGrid to dynamic data, the form of which is not know at compile time. This blog post extends on the method previously described, adding change notification, allowing the DataGrid to synchronise the UI with changes to the bound data and to allow the user to edit the DataGrid&#8217;s contents.</p>
<p>To briefly recap my previous post, the dynamic data is copied to a collection of Rows:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> Row
<span style="color: #008000;">&#123;</span>
  <span style="color: #0600FF; font-weight: bold;">private</span> Dictionary<span style="color: #008000;">&lt;</span><span style="color: #6666cc; font-weight: bold;">string</span>, <span style="color: #6666cc; font-weight: bold;">object</span><span style="color: #008000;">&gt;</span> _data <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Dictionary<span style="color: #008000;">&lt;</span><span style="color: #6666cc; font-weight: bold;">string</span>, <span style="color: #6666cc; font-weight: bold;">object</span><span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
  <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">object</span> <span style="color: #0600FF; font-weight: bold;">this</span> <span style="color: #008000;">&#91;</span><span style="color: #6666cc; font-weight: bold;">string</span> index<span style="color: #008000;">&#93;</span>
  <span style="color: #008000;">&#123;</span>
    get <span style="color: #008000;">&#123;</span> <span style="color: #0600FF; font-weight: bold;">return</span> _data<span style="color: #008000;">&#91;</span>index<span style="color: #008000;">&#93;</span><span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
    set <span style="color: #008000;">&#123;</span> _data<span style="color: #008000;">&#91;</span>index<span style="color: #008000;">&#93;</span> <span style="color: #008000;">=</span> value<span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
  <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Where the row &#8216;properties&#8217; which are implemented via the string indexer bound to the grid via a ValueConverter. The XAML for the DataGrid looks like the following:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;data:DataGrid</span> <span style="color: #000066;">Name</span>=<span style="color: #ff0000;">&quot;_dataGrid&quot;</span> <span style="color: #000066;">AutoGenerateColumns</span>=<span style="color: #ff0000;">&quot;False&quot;</span>  <span style="color: #000066;">IsReadOnly</span>=<span style="color: #ff0000;">&quot;False&quot;</span> <span style="color: #000066;">Margin</span>=<span style="color: #ff0000;">&quot;5&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;data:DataGrid.Columns<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;data:DataGridTextColumn</span> <span style="color: #000066;">Header</span>=<span style="color: #ff0000;">&quot;Forename&quot;</span></span>
<span style="color: #009900;">                                 <span style="color: #000066;">Binding</span>=<span style="color: #ff0000;">&quot;{Binding Converter={StaticResource RowIndexConverter},</span>
<span style="color: #009900;">                                    ConverterParameter=Forename}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;data:DataGridTextColumn</span> <span style="color: #000066;">Header</span>=<span style="color: #ff0000;">&quot;Surname&quot;</span> </span>
<span style="color: #009900;">                                 <span style="color: #000066;">Binding</span>=<span style="color: #ff0000;">&quot;{Binding Converter={StaticResource RowIndexConverter},</span>
<span style="color: #009900;">                                    ConverterParameter=Surname}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
        ...               
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/data:DataGrid.Columns<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/data:DataGrid<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Where the ValueConverter takes the ConverterParameter and uses it to index the bound Row instance:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> RowIndexConverter <span style="color: #008000;">:</span> IValueConverter
<span style="color: #008000;">&#123;</span>
  <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">object</span> Convert<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">object</span> value, Type targetType, <span style="color: #6666cc; font-weight: bold;">object</span> parameter, CultureInfo culture<span style="color: #008000;">&#41;</span>
  <span style="color: #008000;">&#123;</span>
    Row row <span style="color: #008000;">=</span> value <span style="color: #0600FF; font-weight: bold;">as</span> Row<span style="color: #008000;">;</span>
    <span style="color: #6666cc; font-weight: bold;">string</span> index <span style="color: #008000;">=</span> parameter <span style="color: #0600FF; font-weight: bold;">as</span> <span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">;</span>
    <span style="color: #0600FF; font-weight: bold;">return</span> row<span style="color: #008000;">&#91;</span>index<span style="color: #008000;">&#93;</span><span style="color: #008000;">;</span>
  <span style="color: #008000;">&#125;</span> 
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>It is important to note that the Binding does not have a Path defined. As a result, the binding source is the Row instance itself rather than a property of the Row as would more normally be the case when binding data. The rest of the post described how to create a collection view which sorts the collection via the Row&#8217;s string indexer. You can read about this in full in my <a href="http://www.scottlogic.co.uk/blog/colin/2009/04/binding-a-silverlight-datagrid-to-dynamic-data-via-idictionary/">previous blog post</a>.</p>
<p>Now, one question a few people have asked me is how to implement INotifyPropertyChanged on the Row class in order to make the DataGrid editable. Simply implementing INotifyPropertyChanged on the Row class, with events raised from the index setter, will not make the grid editable or synchronised with the bound data. The underlying problem here is that the Binding does not have a Path specified, therefore, the binding framework does not know which property name to look out for when handling PropertyChanged events. Interestingly I would expect the above bindings to be updated if a PropertyChanged event were raised with a null or empty PropertyName string, however they do not.</p>
<p>So if the Binding framework needs a Path for the binding in order for change notification to work, we will have to fabricate one for this purpose! We can modify the Row class as follows, adding a Data property which is simply a reference to the Row instance itself:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> Row <span style="color: #008000;">:</span> INotifyPropertyChanged
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">private</span> Dictionary<span style="color: #008000;">&lt;</span><span style="color: #6666cc; font-weight: bold;">string</span>, <span style="color: #6666cc; font-weight: bold;">object</span><span style="color: #008000;">&gt;</span> _data <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Dictionary<span style="color: #008000;">&lt;</span><span style="color: #6666cc; font-weight: bold;">string</span>, <span style="color: #6666cc; font-weight: bold;">object</span><span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">object</span> <span style="color: #0600FF; font-weight: bold;">this</span> <span style="color: #008000;">&#91;</span><span style="color: #6666cc; font-weight: bold;">string</span> index<span style="color: #008000;">&#93;</span>
    <span style="color: #008000;">&#123;</span>
        get
        <span style="color: #008000;">&#123;</span>
            <span style="color: #0600FF; font-weight: bold;">return</span> _data<span style="color: #008000;">&#91;</span>index<span style="color: #008000;">&#93;</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
        set
        <span style="color: #008000;">&#123;</span>
            _data<span style="color: #008000;">&#91;</span>index<span style="color: #008000;">&#93;</span> <span style="color: #008000;">=</span> value<span style="color: #008000;">;</span>
&nbsp;
            OnPropertyChanged<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Data&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">object</span> Data
    <span style="color: #008000;">&#123;</span>
        get
        <span style="color: #008000;">&#123;</span>
            <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">event</span> PropertyChangedEventHandler PropertyChanged<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">protected</span> <span style="color: #6666cc; font-weight: bold;">void</span> OnPropertyChanged<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span> property<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>PropertyChanged<span style="color: #008000;">!=</span><span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            PropertyChanged<span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">this</span>, <span style="color: #008000;">new</span> PropertyChangedEventArgs<span style="color: #008000;">&#40;</span>property<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>In order to bind this class we modify our bindings so that the source Path points to the Data property:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;">...
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;data:DataGridTextColumn</span> <span style="color: #000066;">Header</span>=<span style="color: #ff0000;">&quot;Forename&quot;</span></span>
<span style="color: #009900;">                           <span style="color: #000066;">Binding</span>=<span style="color: #ff0000;">&quot;{Binding Path=Data, Converter={StaticResource RowIndexConverter},</span>
<span style="color: #009900;">                           ConverterParameter=Forename}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;data:DataGridTextColumn</span> <span style="color: #000066;">Header</span>=<span style="color: #ff0000;">&quot;Forename&quot;</span></span>
<span style="color: #009900;">                           <span style="color: #000066;">Binding</span>=<span style="color: #ff0000;">&quot;{Binding Path=Data, Converter={StaticResource RowIndexConverter},</span>
<span style="color: #009900;">                           ConverterParameter=Surname}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
...</pre></div></div>

<p>With this change in place, all of our bindings are bound to the Row&#8217;s Data property. Again, the Row&#8217;s indexer is being accessed via our value converter. However, if any &#8216;property&#8217; change via the string indexer setter will result in all of our bindings being updated for that Row. I know, it is not the most efficient solution &#8211; but at least it work!</p>
<p>The next problem is making the DataGrid editable. The problem we face here is that all of our bindings are to the same property, Data. When a cell is edited, the binding framework will quite happily call the Data properties setter, with the updated value. However, how do we know which property of the Row was really being set? The only place we hold this information is in the ConverterParameter which is fed to our RowIndexConverter value converter. Fortunately, there is a solution to this problem, when the binding framework updates the bound object, it will first invoke the ConvertBack method on our value converter. This gives us the opportunity to &#8216;capture&#8217; the converter parameter and feed it into the setter of our Data property, as shown below:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> RowIndexConverter <span style="color: #008000;">:</span> IValueConverter
<span style="color: #008000;">&#123;</span>
    <span style="color: #008000;">...</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">object</span> ConvertBack<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">object</span> value, Type targetType,
        <span style="color: #6666cc; font-weight: bold;">object</span> parameter, CultureInfo culture<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #008000;">new</span> PropertyValueChange<span style="color: #008000;">&#40;</span>parameter <span style="color: #0600FF; font-weight: bold;">as</span> <span style="color: #6666cc; font-weight: bold;">string</span>, value<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Where PropertyValueChanged is a simple value object:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> PropertyValueChange
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">string</span> _propertyName<span style="color: #008000;">;</span>
    <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">object</span> _value<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">object</span> Value
    <span style="color: #008000;">&#123;</span>
        get <span style="color: #008000;">&#123;</span> <span style="color: #0600FF; font-weight: bold;">return</span> _value<span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">string</span> PropertyName
    <span style="color: #008000;">&#123;</span>
        get <span style="color: #008000;">&#123;</span> <span style="color: #0600FF; font-weight: bold;">return</span> _propertyName<span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">public</span> PropertyValueChange<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span> propertyName, <span style="color: #6666cc; font-weight: bold;">object</span> value<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        _propertyName <span style="color: #008000;">=</span> propertyName<span style="color: #008000;">;</span>
        _value <span style="color: #008000;">=</span> value<span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>The setter for the Data property will now be invoked with an instance of PropertyValueChanged, giving it all the information it requires to invoke the string indexer with the correct &#8216;property&#8217; name:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> Row <span style="color: #008000;">:</span> INotifyPropertyChanged
<span style="color: #008000;">&#123;</span>
    <span style="color: #008000;">...</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">object</span> Data
    <span style="color: #008000;">&#123;</span>
        get <span style="color: #008000;">&#123;</span> <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
        set
        <span style="color: #008000;">&#123;</span>
            PropertyValueChange setter <span style="color: #008000;">=</span> value <span style="color: #0600FF; font-weight: bold;">as</span> PropertyValueChange<span style="color: #008000;">;</span>
            _data<span style="color: #008000;">&#91;</span>setter<span style="color: #008000;">.</span><span style="color: #0000FF;">PropertyName</span><span style="color: #008000;">&#93;</span> <span style="color: #008000;">=</span> setter<span style="color: #008000;">.</span><span style="color: #0000FF;">Value</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">...</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>With this change in place, we the user is able to edit the data bound to the DataGrid, and the binding ensures that the DataGrid UI is synchronised with any changes to the bound data that may happen elsewhere in our code.</p>
<p>One final thought that struck me is that this technique uses the Binding&#8217;s associated ValueConverter to access the Row&#8217;s string indexer, but what if we wanted to use a ValueConverter for something else like formatting? Fortunately it is a pretty straightforward process to nest one value converter inside another. For details, see the attached project. For now, have quick play with the grid below, where all the columns are editable and the button click event sets the Row&#8217;s Age property demonstrating how the DataGrid is synchronised:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">void</span> Button_Click<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">object</span> sender, RoutedEventArgs e<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #008080; font-style: italic;">// demonstrate the property changes from code-behind still work.</span>
    Random rand <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Random<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #0600FF; font-weight: bold;">foreach</span> <span style="color: #008000;">&#40;</span>var row <span style="color: #0600FF; font-weight: bold;">in</span> _rows<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        row<span style="color: #008000;">&#91;</span><span style="color: #666666;">&quot;Age&quot;</span><span style="color: #008000;">&#93;</span> <span style="color: #008000;">=</span> rand<span style="color: #008000;">.</span><span style="color: #0000FF;">Next</span><span style="color: #008000;">&#40;</span><span style="color: #FF0000;">10</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">+</span> <span style="color: #FF0000;">5</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Also, the Age column has a value converter associated &#8230;</p>
<div id="slPluginHost"> <object id="SilverlightPlugin" width="300" height="300" data="data:application/x-silverlight," type="application/x-silverlight-2" ><param name="source" value="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2009/04/silverlighttable1.xap"/><a href="http://go.microsoft.com/fwlink/?LinkID=124807"  style="text-decoration: none;"> <img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style: none"/></a></object></div>
<p>So there you have it, binding to dynamic data with INotifyPropertyChanged implemented and an editable DataGrid. The only reservation I have with this technique is that I am really bending the binding framework to achieve the results, having a Data property which expects different types for the getter and setter is a little ugly &#8230; use with caution!</p>
<p>You can download the project sourcecode: <a href='http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2009/04/silverlightdynamicbinding2.zip'>silverlightdynamicbinding2.zip</a></p>
<p>Regards, Colin E.</p>

]]></content:encoded>
			<wfw:commentRss>http://www.scottlogic.co.uk/blog/colin/2009/04/binding-a-silverlight-datagrid-to-dynamic-data-part-2-editable-data-and-inotifypropertychanged/feed/</wfw:commentRss>
		<slash:comments>43</slash:comments>
		</item>
		<item>
		<title>Binding a Silverlight DataGrid to dynamic data via IDictionary</title>
		<link>http://www.scottlogic.co.uk/blog/colin/2009/04/binding-a-silverlight-datagrid-to-dynamic-data-via-idictionary/</link>
		<comments>http://www.scottlogic.co.uk/blog/colin/2009/04/binding-a-silverlight-datagrid-to-dynamic-data-via-idictionary/#comments</comments>
		<pubDate>Fri, 17 Apr 2009 15:01:00 +0000</pubDate>
		<dc:creator>Colin Eberhardt</dc:creator>
				<category><![CDATA[codeproject]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[binding]]></category>
		<category><![CDATA[DataGrid]]></category>
		<category><![CDATA[silverlight]]></category>

		<guid isPermaLink="false">http://www.scottlogic.co.uk/blog/colin/?p=251</guid>
		<description><![CDATA[This post demonstrates a technique for binding a Silverlight DataGrid to dynamic data, the structure of which is not know at compile-time &#8230; UPDATE #1: I have extended this technique to add include change notification so that the DataGrid can be made editable. Read all about it in part two. UPDATE #2: This blog post [...]]]></description>
			<content:encoded><![CDATA[
<div class="topsy_widget_data topsy_theme_light-green" style="float: right;margin-left: 0.75em; background: url(data:,%7B%20%22url%22%3A%20%22http%253A%252F%252Fwww.scottlogic.co.uk%252Fblog%252Fcolin%252F2009%252F04%252Fbinding-a-silverlight-datagrid-to-dynamic-data-via-idictionary%252F%22%2C%20%22style%22%3A%20%22big%22%2C%20%22title%22%3A%20%22Binding%20a%20Silverlight%20DataGrid%20to%20dynamic%20data%20via%20IDictionary%20%23%22%20%7D);"></div>
<p>This post demonstrates a technique for binding a Silverlight DataGrid to dynamic data, the structure of which is not know at compile-time &#8230; </p>
<p><b>UPDATE #1</b>: I have extended this technique to add include change notification so that the DataGrid can be made editable. Read all about it in <a href="http://www.scottlogic.co.uk/blog/colin/2009/04/binding-a-silverlight-datagrid-to-dynamic-data-part-2-editable-data-and-inotifypropertychanged/">part two</a>.</p>
<p><strong>UPDATE #2</strong>: This blog post was written with a SL2 DataGrid, for SL3, please see my <a href="http://www.scottlogic.co.uk/blog/colin/2010/03/binding-a-silverlight-3-datagrid-to-dynamic-data-via-idictionary-updated/">updated blog post</a>.</p>
<p>With Silverlight binding data to a DataGrid is a very straightforward process. With an XML datasource, you can simply parse your data via Linq to SQL into an anonymous type then bind the resulting collection to the grid. Just a few simple lines of code. But, what if the data you want to bind to your grid is dynamic? That is, at compile time you do not know how many columns are required, or what their contents is. This is a common problem that Silverlight users have faced <a href="http://silverlight.net/forums/p/54804/187532.aspx">again</a>, and <a href="http://silverlight.net/themes/silverlight/forums/thread.aspx?ThreadID=11570">again</a>, and <a href="http://stackoverflow.com/questions/685513/displaying-a-dynamic-data-structure-in-silverlight-datagrid">again</a> and <a href="http://stackoverflow.com/questions/681495/array-binding-xaml-by-position-silverlight-on-datagrid">again</a>!</p>
<p>The most obvious solution to this problem is to create a dictionary for each row of your DataGrid, and bind your columns to your values via the dictionary&#8217;s string indexer:</p>
<p><code>Binding="{Binding Path=[Name]}"</code></p>
<p>However, unfortunately the PropertyPath syntax used for binding does not understand indexers, making it impossible to bind to a dictionary. </p>
<p>Vladimir Bodurov presents <a href="http://blog.bodurov.com/How-to-bind-Silverlight-DataGrid-from-IEnumerable-of-IDictionary">an ingenious solution to this problem</a> by dynamically generating a new Type based on the values present within the dictionary, i.e. If the dictionary contains the keys &#8220;Name&#8221; and &#8220;Age&#8221;, a Type will be generated that has properties of Name and Age. Crazy stuff! Here I would like to show an alternative method that does not use intermediate Language or other black magic!</p>
<p>We will start with a simple example of a class which can be used to store &#8216;dynamic&#8217; data for rendering in our DataGrid:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> Row
<span style="color: #008000;">&#123;</span>
  <span style="color: #0600FF; font-weight: bold;">private</span> Dictionary<span style="color: #008000;">&lt;</span><span style="color: #6666cc; font-weight: bold;">string</span>, <span style="color: #6666cc; font-weight: bold;">object</span><span style="color: #008000;">&gt;</span> _data <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Dictionary<span style="color: #008000;">&lt;</span><span style="color: #6666cc; font-weight: bold;">string</span>, <span style="color: #6666cc; font-weight: bold;">object</span><span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
  <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">object</span> <span style="color: #0600FF; font-weight: bold;">this</span> <span style="color: #008000;">&#91;</span><span style="color: #6666cc; font-weight: bold;">string</span> index<span style="color: #008000;">&#93;</span>
  <span style="color: #008000;">&#123;</span>
    get <span style="color: #008000;">&#123;</span> <span style="color: #0600FF; font-weight: bold;">return</span> _data<span style="color: #008000;">&#91;</span>index<span style="color: #008000;">&#93;</span><span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
    set <span style="color: #008000;">&#123;</span> _data<span style="color: #008000;">&#91;</span>index<span style="color: #008000;">&#93;</span> <span style="color: #008000;">=</span> value<span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
  <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>We can populate a collection of these objects and associate them with a DataGrid as follows:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">Random rand <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Random<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
var rows <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> ObservableCollection<span style="color: #008000;">&lt;</span>Row<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">for</span> <span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">int</span> i <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span> i <span style="color: #008000;">&lt;</span> <span style="color: #FF0000;">200</span><span style="color: #008000;">;</span> i<span style="color: #008000;">++</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
  Row row <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Row<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
  row<span style="color: #008000;">&#91;</span><span style="color: #666666;">&quot;Forename&quot;</span><span style="color: #008000;">&#93;</span> <span style="color: #008000;">=</span> s_names<span style="color: #008000;">&#91;</span>rand<span style="color: #008000;">.</span><span style="color: #0000FF;">Next</span><span style="color: #008000;">&#40;</span>s_names<span style="color: #008000;">.</span><span style="color: #0000FF;">Length</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#93;</span><span style="color: #008000;">;</span>
  row<span style="color: #008000;">&#91;</span><span style="color: #666666;">&quot;Surname&quot;</span><span style="color: #008000;">&#93;</span> <span style="color: #008000;">=</span> s_surnames<span style="color: #008000;">&#91;</span>rand<span style="color: #008000;">.</span><span style="color: #0000FF;">Next</span><span style="color: #008000;">&#40;</span>s_surnames<span style="color: #008000;">.</span><span style="color: #0000FF;">Length</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#93;</span><span style="color: #008000;">;</span>
  row<span style="color: #008000;">&#91;</span><span style="color: #666666;">&quot;Age&quot;</span><span style="color: #008000;">&#93;</span> <span style="color: #008000;">=</span> rand<span style="color: #008000;">.</span><span style="color: #0000FF;">Next</span><span style="color: #008000;">&#40;</span><span style="color: #FF0000;">40</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">+</span> <span style="color: #FF0000;">10</span><span style="color: #008000;">;</span>
  row<span style="color: #008000;">&#91;</span><span style="color: #666666;">&quot;Shoesize&quot;</span><span style="color: #008000;">&#93;</span> <span style="color: #008000;">=</span> rand<span style="color: #008000;">.</span><span style="color: #0000FF;">Next</span><span style="color: #008000;">&#40;</span><span style="color: #FF0000;">10</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">+</span> <span style="color: #FF0000;">5</span><span style="color: #008000;">;</span>
  rows<span style="color: #008000;">.</span><span style="color: #0000FF;">Add</span><span style="color: #008000;">&#40;</span>row<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
_dataGrid<span style="color: #008000;">.</span><span style="color: #0000FF;">ItemsSource</span> <span style="color: #008000;">=</span> rows<span style="color: #008000;">;</span></pre></div></div>

<p>However, as mentioned earlier, we cannot create a binding path that accesses our Rows indexer, so just how do we bind the columns to our data? </p>
<p>The classic .NET solution to this problem would be to create a custom property descriptor. When databinding, the properties of an object are not accessed directly, rather they are accessed via their associated property descriptor. A custom property descriptor can be supplied for our Row class, via the ICustomTypeDescriptor interface for example, that exposes properties which when accessed invoke our indexer. This is how the .NET DataRowView exposes its properties. Unfortunately there is one small snag here &#8230; Silverlight does not include the required interfaces to create custom properties.</p>
<p>A simple workaround to this problem is to use a binding that binds each row directly to each Row item rather than a specific property of the item, then use a value converter to access the indexer and extract the required value. Here is an example:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;data:DataGrid</span> <span style="color: #000066;">Name</span>=<span style="color: #ff0000;">&quot;_dataGrid&quot;</span> <span style="color: #000066;">AutoGenerateColumns</span>=<span style="color: #ff0000;">&quot;False&quot;</span> <span style="color: #000066;">Height</span>=<span style="color: #ff0000;">&quot;300&quot;</span> <span style="color: #000066;">IsReadOnly</span>=<span style="color: #ff0000;">&quot;False&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;data:DataGrid.Columns<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;data:DataGridTextColumn</span> <span style="color: #000066;">Header</span>=<span style="color: #ff0000;">&quot;Forename&quot;</span> <span style="color: #000066;">Binding</span>=<span style="color: #ff0000;">&quot;{Binding Converter={StaticResource RowIndexConverter}, ConverterParameter=Forename}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span> 
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;data:DataGridTextColumn</span> <span style="color: #000066;">Header</span>=<span style="color: #ff0000;">&quot;Surname&quot;</span> <span style="color: #000066;">Binding</span>=<span style="color: #ff0000;">&quot;{Binding Converter={StaticResource RowIndexConverter}, ConverterParameter=Surname}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span> 
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;data:DataGridTextColumn</span> <span style="color: #000066;">Header</span>=<span style="color: #ff0000;">&quot;Age&quot;</span> <span style="color: #000066;">Binding</span>=<span style="color: #ff0000;">&quot;{Binding Converter={StaticResource RowIndexConverter}, ConverterParameter=Age}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span> 
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;data:DataGridTextColumn</span> <span style="color: #000066;">Header</span>=<span style="color: #ff0000;">&quot;Shoesize&quot;</span> <span style="color: #000066;">Binding</span>=<span style="color: #ff0000;">&quot;{Binding Converter={StaticResource RowIndexConverter}, ConverterParameter=Shoesize}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span> 
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/data:DataGrid.Columns<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/data:DataGrid<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>And here is the value converter:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> RowIndexConverter <span style="color: #008000;">:</span> IValueConverter
<span style="color: #008000;">&#123;</span>
  <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">object</span> Convert<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">object</span> value, Type targetType, <span style="color: #6666cc; font-weight: bold;">object</span> parameter, CultureInfo culture<span style="color: #008000;">&#41;</span>
  <span style="color: #008000;">&#123;</span>
    Row row <span style="color: #008000;">=</span> value <span style="color: #0600FF; font-weight: bold;">as</span> Row<span style="color: #008000;">;</span>
    <span style="color: #6666cc; font-weight: bold;">string</span> index <span style="color: #008000;">=</span> parameter <span style="color: #0600FF; font-weight: bold;">as</span> <span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">;</span>
    <span style="color: #0600FF; font-weight: bold;">return</span> row<span style="color: #008000;">&#91;</span>index<span style="color: #008000;">&#93;</span><span style="color: #008000;">;</span>
  <span style="color: #008000;">&#125;</span>
&nbsp;
  <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">object</span> ConvertBack<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">object</span> value, Type targetType, <span style="color: #6666cc; font-weight: bold;">object</span> parameter, CultureInfo culture<span style="color: #008000;">&#41;</span>
  <span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">throw</span> <span style="color: #008000;">new</span> NotImplementedException<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
  <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>In the above XAML, the binding expression does not have a Path specified, therefore, the binding source is our Row instance rather than a property of the Row. The RowIndexConverter value converter simply uses the supplied ConverterParameter for each column to access the Row indexer and extract the correct value. This works quite nicely, and we are able to see our data within the grid:</p>
<p><a href="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2009/04/grid.png"><img src="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2009/04/grid.png" alt="grid" title="grid" width="296" height="296" class="alignnone size-full wp-image-253" /></a></p>
<p>However, there is one problem here, if you click on the column headers the grid does not sort the data. The columns of a DataGrid have CanUserSort and SortMemberPath properties, however setting these will not help because the DataGrid will expect the bound object to have a property with the given name which of course it does not! To solve this problem (without resorting to dynamically generated types) we need to delve a little deeper into the way in which the DataGrid binds to the data.</p>
<p>A lot of insight can be gained from the documentation of <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.icollectionview(VS.95).aspx">ICollectionView</a>:</p>
<p><i style="margin-left:15px">The DataGrid control uses this interface to access the indicated functionality in the data source assigned to its ItemsSource property. If the ItemsSource implements IList, but does not implement ICollectionView, the DataGrid wraps the ItemsSource in an internal ICollectionView implementation. </i></p>
<p>The ICollectionView interface is responsible for filtering, sorting and grouping of the data bound to the DataGrid. WPF also has the <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.icollectionview.aspx">ICollectionView</a>interface, you can read a good overview of its features on <a href="http://marlongrech.wordpress.com/2008/11/22/icollectionview-explained/">Marlon Grech&#8217;s blog</a>. However, whereas WPF wraps the DataContext itself in a view which is shared across multiple controls, it would appear that Silverlight restricts its usage to the DataGrid. This causes problems if, for example, you want to synchronize the current item between controls (However, Laurent Bugnion has a novel solution for <a href="http://geekswithblogs.net/lbugnion/archive/2009/02/18/simulating-issynchronizedwithcurrentitem-in-silverlight-part-2.aspx">emulating this behaviour</a>).</p>
<p>So, it is the ICollectionView which is responsible for sorting our data. The internal implementation of this interface which the DataGrid creates will expects our object to expose the bound properties, which explains why it does not work. However, if we supply our own ICollectionView interface, we can take control of sorting and implement it ourselves, accessing our &#8216;property&#8217; values via the Row&#8217;s string indexer.</p>
<p>The ICollectionView interface has a lot of methods, events and properties, fortunately I was able to find a suitable implementation of this interface on <a href="http://weblogs.asp.net/manishdalal/archive/2008/12/30/silverlight-datagrid-custom-sorting.aspx">Manish Dalal&#8217;s blog</a>. He had implemented this interface, on a class which extends ObservableCollection, in order to bind a DataGrid to a collection where the data from the server is being paged, hence sorting must be done server side. This gives us pretty much everything we need here, a collection class which is able to manage sorting itself. The only change required is to the ICollectiomView.Refresh() method which is responsible for refreshing the view after the SortDescriptions have changed.</p>
<p>The implementation of this method is as follows:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> SortableCollectionView <span style="color: #008000;">:</span> ObservableCollection<span style="color: #008000;">&lt;</span>Row<span style="color: #008000;">&gt;</span>, ICollectionView
<span style="color: #008000;">&#123;</span>
&nbsp;
  <span style="color: #008000;">...</span>
  <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">void</span> Refresh<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
  <span style="color: #008000;">&#123;</span>
      IEnumerable<span style="color: #008000;">&lt;</span>Row<span style="color: #008000;">&gt;</span> rows <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">;</span>
      IOrderedEnumerable<span style="color: #008000;">&lt;</span>Row<span style="color: #008000;">&gt;</span> orderedRows <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">;</span>
&nbsp;
      <span style="color: #008080; font-style: italic;">// use the OrderBy and ThenBy LINQ extension methods to</span>
      <span style="color: #008080; font-style: italic;">// sort our data</span>
      <span style="color: #6666cc; font-weight: bold;">bool</span> firstSort <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">true</span><span style="color: #008000;">;</span>
      <span style="color: #0600FF; font-weight: bold;">for</span> <span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">int</span> sortIndex <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span> sortIndex <span style="color: #008000;">&lt;</span> _sort<span style="color: #008000;">.</span><span style="color: #0000FF;">Count</span><span style="color: #008000;">;</span> sortIndex<span style="color: #008000;">++</span><span style="color: #008000;">&#41;</span>
      <span style="color: #008000;">&#123;</span>
          SortDescription sort <span style="color: #008000;">=</span> _sort<span style="color: #008000;">&#91;</span>sortIndex<span style="color: #008000;">&#93;</span><span style="color: #008000;">;</span>
          Func<span style="color: #008000;">&lt;</span>Row, <span style="color: #6666cc; font-weight: bold;">object</span><span style="color: #008000;">&gt;</span> function <span style="color: #008000;">=</span> row <span style="color: #008000;">=&gt;</span> row<span style="color: #008000;">&#91;</span>sort<span style="color: #008000;">.</span><span style="color: #0000FF;">PropertyName</span><span style="color: #008000;">&#93;</span><span style="color: #008000;">;</span>
          <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>firstSort<span style="color: #008000;">&#41;</span>
          <span style="color: #008000;">&#123;</span>
              orderedRows <span style="color: #008000;">=</span> sort<span style="color: #008000;">.</span><span style="color: #0000FF;">Direction</span> <span style="color: #008000;">==</span> ListSortDirection<span style="color: #008000;">.</span><span style="color: #0000FF;">Ascending</span> <span style="color: #008000;">?</span>
                  rows<span style="color: #008000;">.</span><span style="color: #0000FF;">OrderBy</span><span style="color: #008000;">&#40;</span>function<span style="color: #008000;">&#41;</span> <span style="color: #008000;">:</span> rows<span style="color: #008000;">.</span><span style="color: #0000FF;">OrderByDescending</span><span style="color: #008000;">&#40;</span>function<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
              firstSort <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">false</span><span style="color: #008000;">;</span>
          <span style="color: #008000;">&#125;</span>
          <span style="color: #0600FF; font-weight: bold;">else</span>
          <span style="color: #008000;">&#123;</span>
              orderedRows <span style="color: #008000;">=</span> sort<span style="color: #008000;">.</span><span style="color: #0000FF;">Direction</span> <span style="color: #008000;">==</span> ListSortDirection<span style="color: #008000;">.</span><span style="color: #0000FF;">Ascending</span> <span style="color: #008000;">?</span>
                  orderedRows<span style="color: #008000;">.</span><span style="color: #0000FF;">ThenBy</span><span style="color: #008000;">&#40;</span>function<span style="color: #008000;">&#41;</span> <span style="color: #008000;">:</span> orderedRows<span style="color: #008000;">.</span><span style="color: #0000FF;">ThenByDescending</span><span style="color: #008000;">&#40;</span>function<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
          <span style="color: #008000;">&#125;</span>
      <span style="color: #008000;">&#125;</span>
&nbsp;
      _suppressCollectionChanged <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">true</span><span style="color: #008000;">;</span>
&nbsp;
      <span style="color: #008080; font-style: italic;">// re-order this collection based on the result if the above</span>
      <span style="color: #6666cc; font-weight: bold;">int</span> index <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
      <span style="color: #0600FF; font-weight: bold;">foreach</span> <span style="color: #008000;">&#40;</span>var row <span style="color: #0600FF; font-weight: bold;">in</span> orderedRows<span style="color: #008000;">&#41;</span>
      <span style="color: #008000;">&#123;</span>
          <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">&#91;</span>index<span style="color: #008000;">++</span><span style="color: #008000;">&#93;</span> <span style="color: #008000;">=</span> row<span style="color: #008000;">;</span>
      <span style="color: #008000;">&#125;</span>
&nbsp;
      _suppressCollectionChanged <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">false</span><span style="color: #008000;">;</span>
&nbsp;
      <span style="color: #008080; font-style: italic;">// raise the required notification</span>
      <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">OnCollectionChanged</span><span style="color: #008000;">&#40;</span>
          <span style="color: #008000;">new</span> NotifyCollectionChangedEventArgs<span style="color: #008000;">&#40;</span>NotifyCollectionChangedAction<span style="color: #008000;">.</span><span style="color: #0000FF;">Reset</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
   <span style="color: #008000;">&#125;</span>
&nbsp;
  <span style="color: #008000;">...</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>When the user clicks on a grid view header, it modifies the bounds ICollectionView.SortDescription to reflect this change in state. The implementation of ICollectiomView from Manish&#8217;s blog invokes the Refresh method whenever the ICollectionView.SortDescription collection changes. In the above implementation we use the OrderBy and ThenBy LINQ extension methods to order the data. Interestingly, OrderBy is a method on IEnumerable, whereas ThenBy is a methods on the IOrderedEnumerable, hence the funny looking logic involving &#8216;firstSort&#8217;. Once the sorting has been performed, the underlying collection is re-ordered to match. The only subtle part is that we use a boolean field, _suppressCollectionChanged to suppress the numerous CollectionChanged events that would be fired by ObservableCollection during this process. Finally we raise NotifyCollectionChanged, resulting in the DataGrid updating to reflect the sort order.</p>
<p>Putting it all together, we simply populate our SortableCollectionView and bind this to the DataGrid, modifying the XAML to explicitly inform the grid that it can sort and which property each column sorts on (usually this is inferred from the Binding Path):</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;data:DataGrid</span> <span style="color: #000066;">Name</span>=<span style="color: #ff0000;">&quot;_dataGrid&quot;</span> <span style="color: #000066;">AutoGenerateColumns</span>=<span style="color: #ff0000;">&quot;False&quot;</span>  <span style="color: #000066;">IsReadOnly</span>=<span style="color: #ff0000;">&quot;False&quot;</span> <span style="color: #000066;">Margin</span>=<span style="color: #ff0000;">&quot;5&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;data:DataGrid.Columns<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;data:DataGridTextColumn</span> <span style="color: #000066;">Header</span>=<span style="color: #ff0000;">&quot;Forename&quot;</span> <span style="color: #000066;">CanUserSort</span>=<span style="color: #ff0000;">&quot;True&quot;</span> <span style="color: #000066;">SortMemberPath</span>=<span style="color: #ff0000;">&quot;Forename&quot;</span> </span>
<span style="color: #009900;">                                  <span style="color: #000066;">Binding</span>=<span style="color: #ff0000;">&quot;{Binding Converter={StaticResource RowIndexConverter},</span>
<span style="color: #009900;">                                    ConverterParameter=Forename}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;data:DataGridTextColumn</span> <span style="color: #000066;">Header</span>=<span style="color: #ff0000;">&quot;Surname&quot;</span> <span style="color: #000066;">CanUserSort</span>=<span style="color: #ff0000;">&quot;True&quot;</span> <span style="color: #000066;">SortMemberPath</span>=<span style="color: #ff0000;">&quot;Surname&quot;</span> </span>
<span style="color: #009900;">                                 <span style="color: #000066;">Binding</span>=<span style="color: #ff0000;">&quot;{Binding Converter={StaticResource RowIndexConverter},</span>
<span style="color: #009900;">                                    ConverterParameter=Surname}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;data:DataGridTextColumn</span> <span style="color: #000066;">Header</span>=<span style="color: #ff0000;">&quot;Age&quot;</span> <span style="color: #000066;">CanUserSort</span>=<span style="color: #ff0000;">&quot;True&quot;</span> <span style="color: #000066;">SortMemberPath</span>=<span style="color: #ff0000;">&quot;Age&quot;</span> </span>
<span style="color: #009900;">                                 <span style="color: #000066;">Binding</span>=<span style="color: #ff0000;">&quot;{Binding Converter={StaticResource RowIndexConverter},</span>
<span style="color: #009900;">                                    ConverterParameter=Age}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;data:DataGridTextColumn</span> <span style="color: #000066;">Header</span>=<span style="color: #ff0000;">&quot;Shoesize&quot;</span> <span style="color: #000066;">CanUserSort</span>=<span style="color: #ff0000;">&quot;True&quot;</span> <span style="color: #000066;">SortMemberPath</span>=<span style="color: #ff0000;">&quot;Shoesize&quot;</span> </span>
<span style="color: #009900;">                                 <span style="color: #000066;">Binding</span>=<span style="color: #ff0000;">&quot;{Binding Converter={StaticResource RowIndexConverter},</span>
<span style="color: #009900;">                                    ConverterParameter=Shoesize}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>                
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/data:DataGrid.Columns<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/data:DataGrid<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>And here it is in action:</p>
<div id="slPluginHost"> <object id="SilverlightPlugin" width="300" height="300" data="data:application/x-silverlight," type="application/x-silverlight-2" ><param name="source" value="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2009/04/silverlighttable.xap"/><a href="http://go.microsoft.com/fwlink/?LinkID=124807"  style="text-decoration: none;"> <img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style: none"/></a></object></div>
<p>You can download the complete solution here: <a href='http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2009/04/silverlightdynamicbinding.zip'>silverlightdynamicbinding.zip</a>.</p>
<p>Regards,<br />
Colin E.</p>

]]></content:encoded>
			<wfw:commentRss>http://www.scottlogic.co.uk/blog/colin/2009/04/binding-a-silverlight-datagrid-to-dynamic-data-via-idictionary/feed/</wfw:commentRss>
		<slash:comments>67</slash:comments>
		</item>
		<item>
		<title>Styling hard-to-reach elements in control templates with attached behaviours</title>
		<link>http://www.scottlogic.co.uk/blog/colin/2009/02/styling-hard-to-reach-elements-in-control-templates-with-attached-behaviours/</link>
		<comments>http://www.scottlogic.co.uk/blog/colin/2009/02/styling-hard-to-reach-elements-in-control-templates-with-attached-behaviours/#comments</comments>
		<pubDate>Tue, 10 Feb 2009 15:29:20 +0000</pubDate>
		<dc:creator>Colin Eberhardt</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[DataGrid]]></category>
		<category><![CDATA[styling]]></category>
		<category><![CDATA[templates]]></category>

		<guid isPermaLink="false">http://www.scottlogic.co.uk/blog/colin/?p=118</guid>
		<description><![CDATA[OK, the title of this blog post is not very snappy, but it is not an easy problem to describe in a few short words. Here&#8217;s the rub, the WPF DataGrid has a select-all button located in the top-left corner, just like Excel and many other grid controls / applications. However, with the default style, [...]]]></description>
			<content:encoded><![CDATA[
<div class="topsy_widget_data topsy_theme_light-green" style="float: right;margin-left: 0.75em; background: url(data:,%7B%20%22url%22%3A%20%22http%253A%252F%252Fwww.scottlogic.co.uk%252Fblog%252Fcolin%252F2009%252F02%252Fstyling-hard-to-reach-elements-in-control-templates-with-attached-behaviours%252F%22%2C%20%22style%22%3A%20%22big%22%2C%20%22title%22%3A%20%22Styling%20hard-to-reach%20elements%20in%20control%20templates%20with%20attached%20behaviours%20%23%22%20%7D);"></div>
<p>OK, the title of this blog post is not very snappy, but it is not an easy problem to describe in a few short words. Here&#8217;s the rub, the WPF DataGrid has a select-all button located in the top-left corner, just like Excel and many other grid controls / applications. However, with the default style, this button is barely visible and I would not be surprised if a user of the grid failed to see it.</p>
<p><a href="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2009/02/select-all.png"><img class="alignnone size-full wp-image-119" title="select-all" src="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2009/02/select-all.png" alt="select-all" width="418" height="220" /></a></p>
<p>Unfortunately restyling this button is not all that straightforward. The more complex WPF controls like the DataGrid and ListView typically expose the template used to construct, and the style applied to their various visual elements.  However, the DataGrid does not expose a style or template for the select-all button.</p>
<p>Fortunately, all is not lost. With WPF, if a control does not expose a style for one of its component parts, you can replicate and replace its entire template. Sometimes this approach feels a little heavy-handed &#8230; &#8220;I can&#8217;t seem to find a way to fit those flashy alloy wheels to my car, so I&#8217;ll just by a new car that already has the wheels I like&#8221;.</p>
<p>I want to explore a more lightweight approach.</p>
<p>Whilst it is usually preferable to modify a controls template from XAML, in cases like this, I prefer the more concise approach of modifying them in code-behind. In order to do this, you need to handle the <a href="http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.loaded.aspx">FrameworkElement.Loaded</a> event on the control whos template you wish to modify. This event is fired after the control&#8217;s visual tree has been constructed, to verify this add a breakpoint in the event handler and inspect the visual tree with <a href="http://www.codeproject.com/KB/WPF/MoleForWPF.aspx">Mole</a>. The image below shows the visual tree of my DataGrid which I have expanded to locate the select-all button.</p>
<p><a href="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2009/02/datagrid-mole.png"><img class="alignnone size-full wp-image-120" title="datagrid-mole" src="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2009/02/datagrid-mole.png" alt="datagrid-mole" width="343" height="297" /></a></p>
<p>You can see that the button is the first element, four steps down the visual tree, therefore it should be easy to locate by walking the visual tree. Once it has been reached we can simply replace its template to the one which we desire:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">void</span> Grid_Loaded<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">object</span> sender, RoutedEventArgs e<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    DependencyObject dep <span style="color: #008000;">=</span> sender <span style="color: #0600FF; font-weight: bold;">as</span> DependencyObject<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">// Navigate down the visual tree to the button</span>
    <span style="color: #0600FF; font-weight: bold;">while</span> <span style="color: #008000;">&#40;</span><span style="color: #008000;">!</span><span style="color: #008000;">&#40;</span>dep <span style="color: #008000;">is</span> Button<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        dep <span style="color: #008000;">=</span> VisualTreeHelper<span style="color: #008000;">.</span><span style="color: #0000FF;">GetChild</span><span style="color: #008000;">&#40;</span>dep, <span style="color: #FF0000;">0</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
    Button button <span style="color: #008000;">=</span> dep <span style="color: #0600FF; font-weight: bold;">as</span> Button<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">// apply our new template</span>
    <span style="color: #6666cc; font-weight: bold;">object</span> res <span style="color: #008000;">=</span> FindResource<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;SelectAllButtonTemplate&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    button<span style="color: #008000;">.</span><span style="color: #0000FF;">Template</span> <span style="color: #008000;">=</span> res <span style="color: #0600FF; font-weight: bold;">as</span> ControlTemplate
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>The template SelectAllButtonTemplate is simply defined as a resource of our Window.</p>
<p>This works just fine for our single grid, but what if we want to use the same trick on multiple DataGrids? (Besides, we have code-behind, which in WPF is a bit of a dirty word!).</p>
<p>The <a href="http://www.codeproject.com/KB/WPF/AttachedBehaviors.aspx">Attached Behaviour</a> pattern is a useful WPF pattern that proves very useful in this situation. In brief, attached properties add state to a your WPF elements, whereas attached behaviours add behaviour. When an attached property becomes associated with a dependency object, an event is raised. We can handle this event and register handlers on the events of the object being attached to, in this case, our DataGrid&#8217;s Loaded event.</p>
<p>The following code is our attached behaviour in its entirety:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #6666cc; font-weight: bold;">class</span> DataGridStyleBehaviour
<span style="color: #008000;">&#123;</span>
    <span style="color: #008080;">#region attached property</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> ControlTemplate GetSelectAllButtonTemplate<span style="color: #008000;">&#40;</span>DataGrid obj<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #008000;">&#40;</span>ControlTemplate<span style="color: #008000;">&#41;</span>obj<span style="color: #008000;">.</span><span style="color: #0000FF;">GetValue</span><span style="color: #008000;">&#40;</span>SelectAllButtonTemplateProperty<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #6666cc; font-weight: bold;">void</span> SetSelectAllButtonTemplate<span style="color: #008000;">&#40;</span>DataGrid obj, ControlTemplate value<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        obj<span style="color: #008000;">.</span><span style="color: #0000FF;">SetValue</span><span style="color: #008000;">&#40;</span>SelectAllButtonTemplateProperty, value<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #0600FF; font-weight: bold;">readonly</span> DependencyProperty SelectAllButtonTemplateProperty <span style="color: #008000;">=</span>
        DependencyProperty<span style="color: #008000;">.</span><span style="color: #0000FF;">RegisterAttached</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;SelectAllButtonTemplate&quot;</span>,
        <span style="color: #008000;">typeof</span><span style="color: #008000;">&#40;</span>ControlTemplate<span style="color: #008000;">&#41;</span>, <span style="color: #008000;">typeof</span><span style="color: #008000;">&#40;</span>DataGridStyleBehaviour<span style="color: #008000;">&#41;</span>,
        <span style="color: #008000;">new</span> UIPropertyMetadata<span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">null</span>, OnSelectAllButtonTemplateChanged<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080;">#endregion</span>
&nbsp;
    <span style="color: #008080;">#region property behaviour</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">// property change event handler for SelectAllButtonTemplate</span>
    <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #6666cc; font-weight: bold;">void</span> OnSelectAllButtonTemplateChanged<span style="color: #008000;">&#40;</span>
        DependencyObject depObj, DependencyPropertyChangedEventArgs e<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        DataGrid grid <span style="color: #008000;">=</span> depObj <span style="color: #0600FF; font-weight: bold;">as</span> DataGrid<span style="color: #008000;">;</span>
        <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>grid <span style="color: #008000;">==</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">&#41;</span>
            <span style="color: #0600FF; font-weight: bold;">return</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">// handle the grid's Loaded event</span>
        grid<span style="color: #008000;">.</span><span style="color: #0000FF;">Loaded</span> <span style="color: #008000;">+=</span> <span style="color: #008000;">new</span> RoutedEventHandler<span style="color: #008000;">&#40;</span>Grid_Loaded<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">// Handles the DataGrid's Loaded event</span>
    <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #6666cc; font-weight: bold;">void</span> Grid_Loaded<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">object</span> sender, RoutedEventArgs e<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        DataGrid grid <span style="color: #008000;">=</span> sender <span style="color: #0600FF; font-weight: bold;">as</span> DataGrid<span style="color: #008000;">;</span>
        DependencyObject dep <span style="color: #008000;">=</span> grid<span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">// Navigate down the visual tree to the button</span>
        <span style="color: #0600FF; font-weight: bold;">while</span> <span style="color: #008000;">&#40;</span><span style="color: #008000;">!</span><span style="color: #008000;">&#40;</span>dep <span style="color: #008000;">is</span> Button<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            dep <span style="color: #008000;">=</span> VisualTreeHelper<span style="color: #008000;">.</span><span style="color: #0000FF;">GetChild</span><span style="color: #008000;">&#40;</span>dep, <span style="color: #FF0000;">0</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
        Button button <span style="color: #008000;">=</span> dep <span style="color: #0600FF; font-weight: bold;">as</span> Button<span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">// apply our new template</span>
        ControlTemplate template <span style="color: #008000;">=</span> GetSelectAllButtonTemplate<span style="color: #008000;">&#40;</span>grid<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        button<span style="color: #008000;">.</span><span style="color: #0000FF;">Template</span> <span style="color: #008000;">=</span> template<span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #008080;">#endregion</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>This attached property can be used as illustrated below, where we apply the SelectAllButtonTemplate from our Window&#8217;s resources to a DataGrid:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Window</span> ...</span>
<span style="color: #009900;">    <span style="color: #000066;">Title</span>=<span style="color: #ff0000;">&quot;BBC News RSS&quot;</span> <span style="color: #000066;">Height</span>=<span style="color: #ff0000;">&quot;300&quot;</span> <span style="color: #000066;">Width</span>=<span style="color: #ff0000;">&quot;400&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
&nbsp;
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Window.Resources<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;XmlDataProvider</span> <span style="color: #000066;">x:Key</span>=<span style="color: #ff0000;">&quot;NewsFeed&quot;</span></span>
<span style="color: #009900;">                     <span style="color: #000066;">Source</span>=<span style="color: #ff0000;">&quot;http://newsrss.bbc.co.uk/rss/newsonline_uk_edition/front_page/rss.xml&quot;</span>  </span>
<span style="color: #009900;">                     <span style="color: #000066;">XPath</span>=<span style="color: #ff0000;">&quot;//item&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ControlTemplate</span> <span style="color: #000066;">x:Key</span>=<span style="color: #ff0000;">&quot;SelectAllButtonTemplate&quot;</span> <span style="color: #000066;">TargetType</span>=<span style="color: #ff0000;">&quot;{x:Type Button}&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Grid<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Rectangle</span>  <span style="color: #000066;">x:Name</span>=<span style="color: #ff0000;">&quot;Border&quot;</span></span>
<span style="color: #009900;">                            <span style="color: #000066;">Fill</span>=<span style="color: #ff0000;">&quot;Pink&quot;</span> </span>
<span style="color: #009900;">                            <span style="color: #000066;">SnapsToDevicePixels</span>=<span style="color: #ff0000;">&quot;True&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Polygon</span>   <span style="color: #000066;">x:Name</span>=<span style="color: #ff0000;">&quot;Arrow&quot;</span></span>
<span style="color: #009900;">                           <span style="color: #000066;">HorizontalAlignment</span>=<span style="color: #ff0000;">&quot;Right&quot;</span></span>
<span style="color: #009900;">                           <span style="color: #000066;">VerticalAlignment</span>=<span style="color: #ff0000;">&quot;Bottom&quot;</span></span>
<span style="color: #009900;">                           <span style="color: #000066;">Margin</span>=<span style="color: #ff0000;">&quot;8,8,3,3&quot;</span></span>
<span style="color: #009900;">                           <span style="color: #000066;">Opacity</span>=<span style="color: #ff0000;">&quot;0.15&quot;</span></span>
<span style="color: #009900;">                           <span style="color: #000066;">Fill</span>=<span style="color: #ff0000;">&quot;Black&quot;</span></span>
<span style="color: #009900;">                           <span style="color: #000066;">Stretch</span>=<span style="color: #ff0000;">&quot;Uniform&quot;</span></span>
<span style="color: #009900;">                           <span style="color: #000066;">Points</span>=<span style="color: #ff0000;">&quot;0,10 10,10 10,0&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/Grid<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>            
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/ControlTemplate<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/Window.Resources<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Grid<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;dg:DataGrid</span> <span style="color: #000066;">Name</span>=<span style="color: #ff0000;">&quot;dataGrid&quot;</span> <span style="color: #000066;">AutoGenerateColumns</span>=<span style="color: #ff0000;">&quot;False&quot;</span> </span>
<span style="color: #009900;">                     <span style="color: #000066;">local:DataGridStyleBehaviour.SelectAllButtonTemplate</span>=<span style="color: #ff0000;">&quot;{StaticResource SelectAllButtonTemplate}&quot;</span></span>
<span style="color: #009900;">                     <span style="color: #000066;">ItemsSource</span>=<span style="color: #ff0000;">&quot;{Binding Source={StaticResource NewsFeed}}&quot;</span> <span style="color: #000066;">RowHeaderWidth</span>=<span style="color: #ff0000;">&quot;25&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;dg:DataGrid.Columns<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;dg:DataGridTextColumn</span> <span style="color: #000066;">Header</span>=<span style="color: #ff0000;">&quot;Title&quot;</span> <span style="color: #000066;">Binding</span>=<span style="color: #ff0000;">&quot;{Binding XPath=title}&quot;</span> <span style="color: #000066;">Width</span>=<span style="color: #ff0000;">&quot;*&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;dg:DataGridHyperlinkColumn</span>   <span style="color: #000066;">Header</span>=<span style="color: #ff0000;">&quot;Url&quot;</span> <span style="color: #000066;">Binding</span>=<span style="color: #ff0000;">&quot;{Binding XPath=link}&quot;</span> <span style="color: #000066;">Width</span>=<span style="color: #ff0000;">&quot;*&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;dg:DataGridTextColumn</span> <span style="color: #000066;">Header</span>=<span style="color: #ff0000;">&quot;Date&quot;</span> <span style="color: #000066;">Binding</span>=<span style="color: #ff0000;">&quot;{Binding XPath=pubDate}&quot;</span> <span style="color: #000066;">Width</span>=<span style="color: #ff0000;">&quot;*&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/dg:DataGrid.Columns<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/dg:DataGrid<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/Grid<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/Window<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>The result is a beautiful pink select-all button that I don&#8217;t think any user would miss in a hurry:</p>
<p><a href="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2009/02/pinkbutton.png"><img class="alignnone size-full wp-image-121" title="pinkbutton" src="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2009/02/pinkbutton.png" alt="pinkbutton" width="368" height="205" /></a></p>
<p>And a clean code-behind file for our Window <img src='http://www.scottlogic.co.uk/blog/colin/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>You can download the demo project for this blog post in the following zip file, <a href="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2009/02/wpfstylinghiddenelements.zip">wpfstylinghiddenelements</a>.</p>
<p>One last thing &#8230; if you are implementing a WPF / Silverlight control, please expose the styles and templates for all component parts of your control!</p>
<p>Regards, Colin E.</p>

]]></content:encoded>
			<wfw:commentRss>http://www.scottlogic.co.uk/blog/colin/2009/02/styling-hard-to-reach-elements-in-control-templates-with-attached-behaviours/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>WPF DataGrid &#8211; Committing changes cell-by-cell</title>
		<link>http://www.scottlogic.co.uk/blog/colin/2009/01/wpf-datagrid-committing-changes-cell-by-cell/</link>
		<comments>http://www.scottlogic.co.uk/blog/colin/2009/01/wpf-datagrid-committing-changes-cell-by-cell/#comments</comments>
		<pubDate>Wed, 21 Jan 2009 17:06:28 +0000</pubDate>
		<dc:creator>Colin Eberhardt</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[DataGrid]]></category>
		<category><![CDATA[IEditableObject]]></category>

		<guid isPermaLink="false">http://wpfadventures.wordpress.com/?p=38</guid>
		<description><![CDATA[In my recent codeproject article on the DataGrid I described a number of techniques for handling the updates to DataTables which are bound to the grid. These examples all worked on the assumption that you want to keep your database synchronised with the DataGrid, with changes being committed on a row-by-row basis, i.e. when the [...]]]></description>
			<content:encoded><![CDATA[
<div class="topsy_widget_data topsy_theme_light-green" style="float: right;margin-left: 0.75em; background: url(data:,%7B%20%22url%22%3A%20%22http%253A%252F%252Fwww.scottlogic.co.uk%252Fblog%252Fcolin%252F2009%252F01%252Fwpf-datagrid-committing-changes-cell-by-cell%252F%22%2C%20%22style%22%3A%20%22big%22%2C%20%22title%22%3A%20%22WPF%20DataGrid%20-%20Committing%20changes%20cell-by-cell%20%23%22%20%7D);"></div>
<p>In my recent <a href="http://www.codeproject.com/KB/WPF/WPFDataGridExamples.aspx">codeproject article on the DataGrid</a> I described a number of techniques for handling the updates to DataTables which are bound to the grid. These examples all worked on the assumption that you want to keep your database synchronised with the DataGrid, with changes being committed on a row-by-row basis, i.e. when the user finishes editing a row the changes are written to the database. The WPF DataGrid operates in a row-oriented manner making this a relatively straightforward scenario to implement.</p>
<p>However, what if you want to commit changes on a cell-by-cell basis? Firstly, lets have a look at the problem in a bit more detail. The following code displays a DataGrid, together with a &#8216;details&#8217; view. Note that IsSynchronizedWithCurrentItem is set to true so that the details view and currently selected item within the grid will remain synchronised:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;DockPanel</span> <span style="color: #000066;">DataContext</span>=<span style="color: #ff0000;">&quot;{Binding Source={StaticResource PersonData}}&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
&nbsp;
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Border</span> <span style="color: #000066;">DockPanel.Dock</span>=<span style="color: #ff0000;">&quot;Bottom&quot;</span> <span style="color: #000066;">Padding</span>=<span style="color: #ff0000;">&quot;10&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Grid</span> <span style="color: #000066;">x:Name</span>=<span style="color: #ff0000;">&quot;RootElement&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Grid.ColumnDefinitions<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ColumnDefinition</span> <span style="color: #000066;">Width</span>=<span style="color: #ff0000;">&quot;*&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ColumnDefinition</span> <span style="color: #000066;">Width</span>=<span style="color: #ff0000;">&quot;1.8*&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/Grid.ColumnDefinitions<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Grid.RowDefinitions<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;RowDefinition</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;RowDefinition</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;RowDefinition</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/Grid.RowDefinitions<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Label</span> <span style="color: #000066;">Content</span>=<span style="color: #ff0000;">&quot;Forename:&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;TextBox</span> <span style="color: #000066;">Grid.Column</span>=<span style="color: #ff0000;">&quot;1&quot;</span> <span style="color: #000066;">Text</span>=<span style="color: #ff0000;">&quot;{Binding Forename}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Label</span> <span style="color: #000066;">Grid.Row</span>=<span style="color: #ff0000;">&quot;1&quot;</span> <span style="color: #000066;">Content</span>=<span style="color: #ff0000;">&quot;Surname:&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;TextBox</span>  <span style="color: #000066;">Grid.Row</span>=<span style="color: #ff0000;">&quot;1&quot;</span> <span style="color: #000066;">Grid.Column</span>=<span style="color: #ff0000;">&quot;1&quot;</span> <span style="color: #000066;">Text</span>=<span style="color: #ff0000;">&quot;{Binding Surname}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Label</span> <span style="color: #000066;">Grid.Row</span>=<span style="color: #ff0000;">&quot;2&quot;</span>  <span style="color: #000066;">Content</span>=<span style="color: #ff0000;">&quot;Age:&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;TextBox</span> <span style="color: #000066;">Grid.Row</span>=<span style="color: #ff0000;">&quot;2&quot;</span>   <span style="color: #000066;">Grid.Column</span>=<span style="color: #ff0000;">&quot;1&quot;</span> <span style="color: #000066;">Text</span>=<span style="color: #ff0000;">&quot;{Binding Age}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/Grid<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/Border<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;dg:DataGrid</span> <span style="color: #000066;">ItemsSource</span>=<span style="color: #ff0000;">&quot;{Binding}&quot;</span> <span style="color: #000066;">Name</span>=<span style="color: #ff0000;">&quot;dataGrid&quot;</span></span>
<span style="color: #009900;">         <span style="color: #000066;">IsSynchronizedWithCurrentItem</span>=<span style="color: #ff0000;">&quot;true&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/DockPanel<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>The &#8216;PersonData&#8217; in this case is a DataTable that is constructed in the code-behind.</p>
<p>Now, with this example, if you make changes to a persons surname, then click on the age cell and make changes there, the changes in surname are not reflected in the details view below:</p>
<p><a href="http://wpfadventures.files.wordpress.com/2008/11/rownotcommitted.png"><img class="alignnone size-full wp-image-39" title="rownotcommitted" src="http://wpfadventures.files.wordpress.com/2008/11/rownotcommitted.png" alt="rownotcommitted" width="299" height="299" /></a></p>
<p>In the above example the user has entered the surname &#8220;Blunt&#8221; and has moved onto the age cell, however the changes are not reflected in the details view below.</p>
<p>Why is this?</p>
<p>The reason is that when you bind to a DataTable, you are actually binding to your DataTable&#8217;s DefaultView, which is of type DataView. As a result, each row of your table will be bound to a DataRowView. If you look at the documentation for <a href="http://msdn.microsoft.com/en-us/library/system.data.datarowview.aspx">DataRowView</a> you will find that it implements the <a href="http://www.google.co.uk/url?sa=t&amp;source=web&amp;ct=res&amp;cd=1&amp;url=http%3A%2F%2Fmsdn.microsoft.com%2Fen-us%2Flibrary%2Fsystem.componentmodel.ieditableobject.aspx&amp;ei=SQ4wSZy0KIbgwgHOmPWNCw&amp;usg=AFQjCNHpZx0Bm5eAgfjjXYEC125a0PnBKQ&amp;sig2=A8KtQWJwPJjE8t91q_0lFA">IEditableObject</a> interface which is the significant factor here. This interface allows you to perform trasnactional changes to your object, i.e. you can change the object&#8217;s properties within a &#8216;transaction&#8217;, then commit then all in a single atomic action. By default, when you bind to a DataGrid this occurs when the user finishes editing a row, either by moving focus or hitting Enter. In order to allow cell-by-cell changes, we need to commit each time the user moves from one cell to the next in the currently selected row.</p>
<p>The DataGrid exposes a CellEditEnding event which looks like a good candidate for this, from the event arguments we can locate the current EditingElement (i.e. the TextBox which now occupies or cell that is in edit mode), the cell&#8217;s Column and Row, and from here we can locate the Row.Item whcih is our bound DataRowView. You might think that we can just commit the change in this event handler, however, this is an &#8216;Ending&#8217; event, not an &#8216;Ended&#8217; event. In other words the value has not yet been written to the row. This catches me out far too often &#8211; as does its RowEditEnding counterpart!</p>
<p>So, if we cannot commit the edit here, how about the CurrentCellChanged event? however this event does not tell us which cell we just left. Although a simple combination of the two provides the effect we are after:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">private</span> DataRowView rowBeingEdited <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">void</span> dataGrid_CellEditEnding<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">object</span> sender,
                                  DataGridCellEditEndingEventArgs e<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    DataRowView rowView <span style="color: #008000;">=</span> e<span style="color: #008000;">.</span><span style="color: #0000FF;">Row</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Item</span> <span style="color: #0600FF; font-weight: bold;">as</span> DataRowView<span style="color: #008000;">;</span>
    rowBeingEdited <span style="color: #008000;">=</span> rowView<span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">void</span> dataGrid_CurrentCellChanged<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">object</span> sender, EventArgs e<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>rowBeingEdited <span style="color: #008000;">!=</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        rowBeingEdited<span style="color: #008000;">.</span><span style="color: #0000FF;">EndEdit</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>With this change in place, changes are committed cell-by-cell and the two view remain synchronised:</p>
<p><a href="http://wpfadventures.files.wordpress.com/2008/11/cellsynchronized.png"><img class="alignnone size-full wp-image-40" title="cellsynchronized" src="http://wpfadventures.files.wordpress.com/2008/11/cellsynchronized.png" alt="cellsynchronized" width="299" height="299" /></a></p>
<p>You can download an example project, <a href="http://wpfadventures.files.wordpress.com/2008/11/wpfdatagridcellbycellcommits.doc">wpfdatagridcellbycellcommits</a>, changing the file extension from .doc to .zip.</p>
<p>Regards, Colin E.</p>

]]></content:encoded>
			<wfw:commentRss>http://www.scottlogic.co.uk/blog/colin/2009/01/wpf-datagrid-committing-changes-cell-by-cell/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>WPF DataGrid &#8211; detecting the column, cell and row that has been clicked</title>
		<link>http://www.scottlogic.co.uk/blog/colin/2008/12/wpf-datagrid-detecting-clicked-cell-and-row/</link>
		<comments>http://www.scottlogic.co.uk/blog/colin/2008/12/wpf-datagrid-detecting-clicked-cell-and-row/#comments</comments>
		<pubDate>Tue, 02 Dec 2008 17:00:47 +0000</pubDate>
		<dc:creator>Colin Eberhardt</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[DataGrid]]></category>

		<guid isPermaLink="false">http://wpfadventures.wordpress.com/?p=59</guid>
		<description><![CDATA[The WPF DataGrid is a very flexible tool, however in its current state certain simple tasks can prove to be rather tricky. A fairly common task when working with DataGrid is detecting which row, or cell a user has clicked on, or whether they clicked a column header. You might expect this information to be [...]]]></description>
			<content:encoded><![CDATA[
<div class="topsy_widget_data topsy_theme_light-green" style="float: right;margin-left: 0.75em; background: url(data:,%7B%20%22url%22%3A%20%22http%253A%252F%252Fwww.scottlogic.co.uk%252Fblog%252Fcolin%252F2008%252F12%252Fwpf-datagrid-detecting-clicked-cell-and-row%252F%22%2C%20%22style%22%3A%20%22big%22%2C%20%22title%22%3A%20%22WPF%20DataGrid%20-%20detecting%20the%20column%2C%20cell%20and%20row%20that%20has%20been%20clicked%20%23%22%20%7D);"></div>
<p>The WPF DataGrid is a very flexible tool, however in its current state certain simple tasks can prove to be rather tricky. A fairly common task when working with DataGrid is detecting which row, or cell a user has clicked on, or whether they clicked a column header. You might expect this information to be readily available in the form of events, after all, the Windows Forms DataGridView has <a href="msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.cellclick.aspx">CellClicked</a> and <a href="msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.columnheadermouseclick.aspx">ColumnHeaderMouseClick</a> events (among many others). However, sadly this is not the case. In order to implement this behaviour you have to understand the visual tree of the DataGrid and how it can be navigated.</p>
<p>Let&#8217;s say for example you wanted to find the DataGrid item (cell, row, header) that was clicked when the right mouse button is released. Firstly, we add an event handler for the mouse click in our code-behind:</p>
<p>XAML:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;dg:DataGrid</span> <span style="color: #000066;">Name</span>=<span style="color: #ff0000;">&quot;DataGrid&quot;</span></span>
<span style="color: #009900;">             <span style="color: #000066;">MouseRightButtonUp</span>=<span style="color: #ff0000;">&quot;DataGrid_MouseRightButtonUp&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span></pre></div></div>

<p>C#:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">void</span> DataGrid_MouseRightButtonUp<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">object</span> sender,
                                        MouseButtonEventArgs e<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>The above event is a &#8216;bubbling&#8217; event, which means that it it started on the element that was originally clicked (for example a TextBlock which renders the cell&#8217;s value within a DataGridCell), then bubbled up the logical tree until it reaches our event handler in the Window. The e.OriginalSource property gives us access to the element that initiated this event.</p>
<p>The problem is that while we have access to the lement which was clicked on, this element is part of the control or data template of the element that we are really interested, the cell or header. The WPF rich-content model means that our cells could contain all sorts of visual element, therefore we have no way of guessing exactly what e.OriginalSource will be. However, the one thing of which we can be certain is that this element is a child of the element which we are interested in.</p>
<p>If you place a bearkpoint within yoru event handler, you can then use the excellent <a href="http://karlshifflett.wordpress.com/mole-for-visual-studio/">Mole</a> debug visualiser to locate the clicked element within the visual tree as illustrated below:</p>
<p><a href="http://wpfadventures.files.wordpress.com/2008/12/dgvisualtree.png"><img class="alignnone size-full wp-image-60" title="dgvisualtree" src="http://wpfadventures.files.wordpress.com/2008/12/dgvisualtree.png" alt="dgvisualtree" width="450" height="428" /></a></p>
<p>As you can see, the visual tree is a complex beast! I have highlighted the items of interest:</p>
<ol>
<li>The <strong>TextBlock</strong>, which is the element I clicked on, which is e.OriginalSource parameter.</li>
<li>The <strong>DataGridCell</strong>, the cell which was clicked on.</li>
<li>The <strong>DataGridRow </strong>which the cell belongs to.</li>
<li>And finally, the <strong>DataGrid</strong>.</li>
</ol>
<p>Therefore, in order to locate the cell and row that was clicked on we must navigate up the Visual Tree, searching by type:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">void</span> DataGrid_MouseRightButtonUp<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">object</span> sender,
                                                  MouseButtonEventArgs e<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    DependencyObject dep <span style="color: #008000;">=</span> <span style="color: #008000;">&#40;</span>DependencyObject<span style="color: #008000;">&#41;</span>e<span style="color: #008000;">.</span><span style="color: #0000FF;">OriginalSource</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">// iteratively traverse the visual tree</span>
    <span style="color: #0600FF; font-weight: bold;">while</span> <span style="color: #008000;">&#40;</span><span style="color: #008000;">&#40;</span>dep <span style="color: #008000;">!=</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&amp;</span>amp<span style="color: #008000;">;&amp;</span>amp<span style="color: #008000;">;</span>
            <span style="color: #008000;">!</span><span style="color: #008000;">&#40;</span>dep <span style="color: #008000;">is</span> DataGridCell<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&amp;</span>amp<span style="color: #008000;">;&amp;</span>amp<span style="color: #008000;">;</span>
            <span style="color: #008000;">!</span><span style="color: #008000;">&#40;</span>dep <span style="color: #008000;">is</span> DataGridColumnHeader<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        dep <span style="color: #008000;">=</span> VisualTreeHelper<span style="color: #008000;">.</span><span style="color: #0000FF;">GetParent</span><span style="color: #008000;">&#40;</span>dep<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>dep <span style="color: #008000;">==</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">&#41;</span>
        <span style="color: #0600FF; font-weight: bold;">return</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>dep <span style="color: #008000;">is</span> DataGridColumnHeader<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        DataGridColumnHeader columnHeader <span style="color: #008000;">=</span> dep <span style="color: #0600FF; font-weight: bold;">as</span> DataGridColumnHeader<span style="color: #008000;">;</span>
        <span style="color: #008080; font-style: italic;">// do something</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>dep <span style="color: #008000;">is</span> DataGridCell<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        DataGridCell cell <span style="color: #008000;">=</span> dep <span style="color: #0600FF; font-weight: bold;">as</span> DataGridCell<span style="color: #008000;">;</span>
        <span style="color: #008080; font-style: italic;">// do something</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Fantastic, we have now have our header and cell. All that&#8217;s left to do is extract the cell&#8217;s row and column indices, and cell value. Wait a minute &#8230; where are the cell.RowIndex and cell.ColumnIndex properties? It looks like there&#8217;s more work to be done.</p>
<p>Once we have navigated up the tree to the DataGridCell, we can continue our journey upwards to obtain the DataGridRow:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>dep <span style="color: #008000;">is</span> DataGridCell<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    DataGridCell cell <span style="color: #008000;">=</span> dep <span style="color: #0600FF; font-weight: bold;">as</span> DataGridCell<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">// navigate further up the tree</span>
    <span style="color: #0600FF; font-weight: bold;">while</span> <span style="color: #008000;">&#40;</span><span style="color: #008000;">&#40;</span>dep <span style="color: #008000;">!=</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&amp;</span>amp<span style="color: #008000;">;&amp;</span>amp<span style="color: #008000;">;</span> <span style="color: #008000;">!</span><span style="color: #008000;">&#40;</span>dep <span style="color: #008000;">is</span> DataGridRow<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        dep <span style="color: #008000;">=</span> VisualTreeHelper<span style="color: #008000;">.</span><span style="color: #0000FF;">GetParent</span><span style="color: #008000;">&#40;</span>dep<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    DataGridRow row <span style="color: #008000;">=</span> dep <span style="color: #0600FF; font-weight: bold;">as</span> DataGridRow<span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Does the DataGridRow have a RowIndex property? I think you can guess the answer to that question.</p>
<p>The DataGrid is an <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.aspx">ItemsControl</a> &#8211; WPF users are probably most familiar with the ListView which is also an ItemsControl whcih has a number of similarities with the DataGrid. In the ItemsControl terminology, the DataGridRow is an ItemContainer and the DataGrid has an ItemContainerGenerator associated with it for generating the rows. I don&#8217;t want to go into the details of how ItemContainers work, Dr. WPF has a good <a href="http://www.drwpf.com/blog/ItemsControlSeries/tabid/59/Default.aspx">series on the ItemsControl</a> for those who are interested. The following code can be used to determine the index of a row:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">int</span> FindRowIndex<span style="color: #008000;">&#40;</span>DataGridRow row<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    DataGrid dataGrid <span style="color: #008000;">=</span>
        ItemsControl<span style="color: #008000;">.</span><span style="color: #0000FF;">ItemsControlFromItemContainer</span><span style="color: #008000;">&#40;</span>row<span style="color: #008000;">&#41;</span>
        <span style="color: #0600FF; font-weight: bold;">as</span> DataGrid<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #6666cc; font-weight: bold;">int</span> index <span style="color: #008000;">=</span> dataGrid<span style="color: #008000;">.</span><span style="color: #0000FF;">ItemContainerGenerator</span><span style="color: #008000;">.</span>
        <span style="color: #0000FF;">IndexFromContainer</span><span style="color: #008000;">&#40;</span>row<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">return</span> index<span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Now that we have the row index, the column index is thankfully a little easier to locate, cell.Column.DisplayIndex does the trick. The final piece of information which we might like is the cell value. Is there a cell.Value properly? don&#8217;t make me laugh!</p>
<p>The following method determines the property binding for the cells column, then extracts the value from the data items associated with the row:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">object</span> ExtractBoundValue<span style="color: #008000;">&#40;</span>DataGridRow row,
                                 DataGridCell cell<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #008080; font-style: italic;">// find the column that this cell belongs to</span>
    DataGridBoundColumn col <span style="color: #008000;">=</span>
       cell<span style="color: #008000;">.</span><span style="color: #0000FF;">Column</span> <span style="color: #0600FF; font-weight: bold;">as</span> DataGridBoundColumn<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">// find the property that this column is bound to</span>
    Binding binding <span style="color: #008000;">=</span> col<span style="color: #008000;">.</span><span style="color: #0000FF;">Binding</span> <span style="color: #0600FF; font-weight: bold;">as</span> Binding<span style="color: #008000;">;</span>
    <span style="color: #6666cc; font-weight: bold;">string</span> boundPropertyName <span style="color: #008000;">=</span> binding<span style="color: #008000;">.</span><span style="color: #0000FF;">Path</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Path</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">// find the object that is related to this row</span>
    <span style="color: #6666cc; font-weight: bold;">object</span> data <span style="color: #008000;">=</span> row<span style="color: #008000;">.</span><span style="color: #0000FF;">Item</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">// extract the property value</span>
    PropertyDescriptorCollection properties <span style="color: #008000;">=</span>
        TypeDescriptor<span style="color: #008000;">.</span><span style="color: #0000FF;">GetProperties</span><span style="color: #008000;">&#40;</span>data<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    PropertyDescriptor property <span style="color: #008000;">=</span> properties<span style="color: #008000;">&#91;</span>boundPropertyName<span style="color: #008000;">&#93;</span><span style="color: #008000;">;</span>
    <span style="color: #6666cc; font-weight: bold;">object</span> value <span style="color: #008000;">=</span> property<span style="color: #008000;">.</span><span style="color: #0000FF;">GetValue</span><span style="color: #008000;">&#40;</span>data<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">return</span> value<span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Putting it all together, this blog post has a small smaple application which displays the header index and value, or cell&#8217;s row/column indices and value in response to a right mouse click:</p>
<p><a href="http://wpfadventures.files.wordpress.com/2008/12/clickedvalue.png"><img class="alignnone size-full wp-image-61" title="clickedvalue" src="http://wpfadventures.files.wordpress.com/2008/12/clickedvalue.png" alt="clickedvalue" width="299" height="299" /></a></p>
<p>The sample project can be download, <a href="http://wpfadventures.files.wordpress.com/2008/12/wpfdatagridmouseclicks.doc">wpfdatagridmouseclicks</a>, changing the file extension from .doc to .zip.</p>
<p>Regards, Colin E.</p>

]]></content:encoded>
			<wfw:commentRss>http://www.scottlogic.co.uk/blog/colin/2008/12/wpf-datagrid-detecting-clicked-cell-and-row/feed/</wfw:commentRss>
		<slash:comments>48</slash:comments>
		</item>
		<item>
		<title>Multiselect DataGrid with CheckBoxes</title>
		<link>http://www.scottlogic.co.uk/blog/colin/2008/11/multiselect-datagrid-with-checkboxes/</link>
		<comments>http://www.scottlogic.co.uk/blog/colin/2008/11/multiselect-datagrid-with-checkboxes/#comments</comments>
		<pubDate>Wed, 26 Nov 2008 16:59:39 +0000</pubDate>
		<dc:creator>Colin Eberhardt</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[DataGrid]]></category>

		<guid isPermaLink="false">http://wpfadventures.wordpress.com/?p=6</guid>
		<description><![CDATA[I am currently very interested in the new WPF DataGrid which was released on codeplex recently. Someone posted an interesting question in the codeplex forums asking about whether it would be possible to configure the DataGrid so that a user can make multiple row selections via checkboxes which are associated with each row. I thought [...]]]></description>
			<content:encoded><![CDATA[
<div class="topsy_widget_data topsy_theme_light-green" style="float: right;margin-left: 0.75em; background: url(data:,%7B%20%22url%22%3A%20%22http%253A%252F%252Fwww.scottlogic.co.uk%252Fblog%252Fcolin%252F2008%252F11%252Fmultiselect-datagrid-with-checkboxes%252F%22%2C%20%22style%22%3A%20%22big%22%2C%20%22title%22%3A%20%22Multiselect%20DataGrid%20with%20CheckBoxes%20%23%22%20%7D);"></div>
<p>I am currently very interested in the new WPF DataGrid which was released on <a href="http://www.codeplex.com/wpf">codeplex</a> recently. Someone posted an interesting question in the <a href="http://www.codeplex.com/wpf/Thread/View.aspx">codeplex forums</a> asking about whether it would be possible to configure the DataGrid so that a user can make multiple row selections via checkboxes which are associated with each row. I thought that this sounded like an excellent idea &#8211; afterall, the standard behaviour of ctrl-leftclick might be intuitive to the computer savvy, however you can bet the average user (which is certainly the majority) does not know this.</p>
<p>Fortunately the solution is quite simple to implement in WPF:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;dg:DataGrid</span> <span style="color: #000066;">ItemsSource</span>=<span style="color: #ff0000;">&quot;{Binding}&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;dg:DataGrid.RowHeaderTemplate<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;DataTemplate<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Grid<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;CheckBox</span> <span style="color: #000066;">IsChecked</span>=<span style="color: #ff0000;">&quot;{Binding Path=IsSelected, Mode=TwoWay,</span>
<span style="color: #009900;">                  RelativeSource={RelativeSource FindAncestor,</span>
<span style="color: #009900;">                  AncestorType={x:Type dg:DataGridRow}}}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/Grid<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/DataTemplate<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/dg:DataGrid.RowHeaderTemplate<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/dg:DataGrid<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>The above code provides a DataTemplate for the RowHeader allowing us to render a CheckBox for each row. The IsChecked property uses a RelativeSource binding which navigates the Visual Tree to locate the first ancestor of type DataGridRow. From here the IsSelected property which dictates that the selected state of the row is available. The binding is TwoWay so that ctrl-leftclick behaviour is still visible.</p>
<p>The result is illustrated below:</p>
<p><a href="http://wpfadventures.files.wordpress.com/2008/11/multiselect.png"><img class="alignnone size-full wp-image-8" title="multiselect" src="http://wpfadventures.files.wordpress.com/2008/11/multiselect.png" alt="multiselect" width="215" height="196" /></a></p>
<p>The above example is a concise illustration of the beauty of WPF. Performing the above customisation of the DataGridView in Windows Forms would be at least an afternoons work. However the solution is not without its problems, if you try the above you will find that the checkboxes are rather difficult to click on because the mouse cursor will be displaying the up-down arrow that indicates that it is currently over the gripper that allows you to specify the row height.</p>
<p>Finding the cause of this means delving deep into the DataGrid control templates &#8230;</p>
<p>The template for the DataGridRowHeader is given below (in edited form):</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Style</span> <span style="color: #000066;">x:Key</span>=<span style="color: #ff0000;">&quot;{x:Type dgp:DataGridRowHeader}&quot;</span></span>
<span style="color: #009900;">       <span style="color: #000066;">TargetType</span>=<span style="color: #ff0000;">&quot;{x:Type dgp:DataGridRowHeader}&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Setter</span> <span style="color: #000066;">Property</span>=<span style="color: #ff0000;">&quot;Template&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Setter.Value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ControlTemplate</span> <span style="color: #000066;">TargetType</span>=<span style="color: #ff0000;">&quot;{x:Type dgp:DataGridRowHeader}&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Grid<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
          ... snipped header content + validation error indicator ...
          <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Thumb</span> <span style="color: #000066;">x:Name</span>=<span style="color: #ff0000;">&quot;PART_TopHeaderGripper&quot;</span></span>
<span style="color: #009900;">                 <span style="color: #000066;">VerticalAlignment</span>=<span style="color: #ff0000;">&quot;Top&quot;</span></span>
<span style="color: #009900;">                 <span style="color: #000066;">Style</span>=<span style="color: #ff0000;">&quot;{StaticResource RowHeaderGripperStyle}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
          <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Thumb</span> <span style="color: #000066;">x:Name</span>=<span style="color: #ff0000;">&quot;PART_BottomHeaderGripper&quot;</span></span>
<span style="color: #009900;">                 <span style="color: #000066;">VerticalAlignment</span>=<span style="color: #ff0000;">&quot;Bottom&quot;</span></span>
<span style="color: #009900;">                 <span style="color: #000066;">Style</span>=<span style="color: #ff0000;">&quot;{StaticResource RowHeaderGripperStyle}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/Grid<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/ControlTemplate<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/Setter.Value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/Setter<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/Style<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>The header template includes a pair of grippers. The visible state of these is toggled depending on the row&#8217;s location (i.e. there is no top gripper on the first row), and whether the DataGrid CanResizeRows is true.</p>
<p>The RowHeaderGripperStyle specifies a Transparent background for the grippers which renders them invisible. If we change this to Green we can see the culprits:</p>
<p><a href="http://wpfadventures.files.wordpress.com/2008/11/datagridselectproblem.png"><img class="alignnone size-full wp-image-9" title="datagridselectproblem" src="http://wpfadventures.files.wordpress.com/2008/11/datagridselectproblem.png" alt="datagridselectproblem" width="214" height="210" /></a></p>
<p>In order to allow our Checkboxes to be clickable, we simply reduce the height of the grippers as follows:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Style</span> <span style="color: #000066;">x:Key</span>=<span style="color: #ff0000;">&quot;RowHeaderGripperStyle&quot;</span> <span style="color: #000066;">TargetType</span>=<span style="color: #ff0000;">&quot;{x:Type Thumb}&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Setter</span> <span style="color: #000066;">Property</span>=<span style="color: #ff0000;">&quot;Height&quot;</span> <span style="color: #000066;">Value</span>=<span style="color: #ff0000;">&quot;2&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Setter</span> <span style="color: #000066;">Property</span>=<span style="color: #ff0000;">&quot;Background&quot;</span> <span style="color: #000066;">Value</span>=<span style="color: #ff0000;">&quot;Green&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Setter</span> <span style="color: #000066;">Property</span>=<span style="color: #ff0000;">&quot;Cursor&quot;</span> <span style="color: #000066;">Value</span>=<span style="color: #ff0000;">&quot;SizeNS&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Setter</span> <span style="color: #000066;">Property</span>=<span style="color: #ff0000;">&quot;Template&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Setter.Value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ControlTemplate</span> <span style="color: #000066;">TargetType</span>=<span style="color: #ff0000;">&quot;{x:Type Thumb}&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Border</span> <span style="color: #000066;">Padding</span>=<span style="color: #ff0000;">&quot;{TemplateBinding Padding}&quot;</span></span>
<span style="color: #009900;">                <span style="color: #000066;">Background</span>=<span style="color: #ff0000;">&quot;{TemplateBinding Background}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/ControlTemplate<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/Setter.Value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/Setter<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/Style<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Unfortunately this means that we have to duplicate the DataGrid parts; the DataGridRowHeader template and the above style, in order to perform this customisation. The Beauty of XAML and a Beast of a control template!</p>
<p>You can download the demo project, <a href="http://wpfadventures.files.wordpress.com/2008/11/wpfdatagridmultiselect.doc">wpfdatagridmultiselect</a>, changing the file extension from .doc to .zip.</p>
<p>Regards, Colin E.</p>
<p>P.S. You can achieve the same effect with a ListView as detailed in <a href="http://weblogs.asp.net/marianor/archive/2008/02/04/multiselect-listview-with-checkboxes-in-wpf.aspx">this blog post</a>.</p>

]]></content:encoded>
			<wfw:commentRss>http://www.scottlogic.co.uk/blog/colin/2008/11/multiselect-datagrid-with-checkboxes/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
	</channel>
</rss>

