<?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; binding</title>
	<atom:link href="http://www.scottlogic.co.uk/blog/colin/tag/binding/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>A Simple Pattern for Creating Re-useable UserControls in WPF / Silverlight</title>
		<link>http://www.scottlogic.co.uk/blog/colin/2012/02/a-simple-pattern-for-creating-re-useable-usercontrols-in-wpf-silverlight/</link>
		<comments>http://www.scottlogic.co.uk/blog/colin/2012/02/a-simple-pattern-for-creating-re-useable-usercontrols-in-wpf-silverlight/#comments</comments>
		<pubDate>Mon, 06 Feb 2012 16:35:41 +0000</pubDate>
		<dc:creator>Colin Eberhardt</dc:creator>
				<category><![CDATA[codeproject]]></category>
		<category><![CDATA[binding]]></category>
		<category><![CDATA[usercontrol]]></category>

		<guid isPermaLink="false">http://www.scottlogic.co.uk/blog/colin/?p=1958</guid>
		<description><![CDATA[This blog post provides step-by-step instructions for creating a user control, which exposes bindable properties, in WPF and Silverlight. The post covers dependency properties, and how to manage DataContext inheritance. When building user interfaces you will often find yourself repeating the same UI patterns across your application. After all, users like to be presented with [...]]]></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%252F2012%252F02%252Fa-simple-pattern-for-creating-re-useable-usercontrols-in-wpf-silverlight%252F%22%2C%20%22style%22%3A%20%22big%22%2C%20%22title%22%3A%20%22A%20Simple%20Pattern%20for%20Creating%20Re-useable%20UserControls%20in%20WPF%20%2F%20Silverlight%20%23%22%20%7D);"></div>
<p><em>This blog post provides step-by-step instructions for creating a user control, which exposes bindable properties, in WPF and Silverlight. The post covers dependency properties, and how to manage DataContext inheritance.</em></p>
<p>When building user interfaces you will often find yourself repeating the same UI patterns across your application. After all, users like to be presented with a consistent interface, so re-use makes sense. The WPF and Silverlight frameworks provide custom controls and user controls as a mechanism for re-using blocks of UI elements. Custom controls are rather special, with the logic being de-coupled from the XAML in order to support templating. For most needs, the simpler user control is more appropriate.</p>
<p>From participating in sites like StackOverflow I have noticed that whilst most people understand how to create a user control, which allows them to ‘stamp out’ the same XAML in multiple places, many struggle with how to make their user controls flexible by exposing properties that configure how it looks or behaves. This blog post will walk through a simple example, showing you how to create a user control, add dependency properties, wire them to the user control XAML and make a truly re-useable control.</p>
<p>We’ll start with a very simple example, an application that displays a simple form field which consists of a name and a value:</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;UserControl</span> <span style="color: #000066;">x:Class</span>=<span style="color: #ff0000;">&quot;UserControlExample.MainPage&quot;</span></span>
<span style="color: #009900;">    ...<span style="color: #000000; font-weight: bold;">&gt;</span></span>
&nbsp;
  <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;LayoutRoot&quot;</span> <span style="color: #000066;">Background</span>=<span style="color: #ff0000;">&quot;White&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;StackPanel</span> <span style="color: #000066;">Orientation</span>=<span style="color: #ff0000;">&quot;Horizontal&quot;</span></span>
<span style="color: #009900;">                <span style="color: #000066;">VerticalAlignment</span>=<span style="color: #ff0000;">&quot;Top&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;TextBlock</span> <span style="color: #000066;">Text</span>=<span style="color: #ff0000;">&quot;Shoesize:&quot;</span></span>
<span style="color: #009900;">                 <span style="color: #000066;">Width</span>=<span style="color: #ff0000;">&quot;100&quot;</span></span>
<span style="color: #009900;">                 <span style="color: #000066;">VerticalAlignment</span>=<span style="color: #ff0000;">&quot;Center&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;">Text</span>=<span style="color: #ff0000;">&quot;{Binding Path=Shoesize}&quot;</span></span>
<span style="color: #009900;">               <span style="color: #000066;">Width</span>=<span style="color: #ff0000;">&quot;100&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/StackPanel<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;/UserControl<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>This UI is bound to a simple model object that implements <code>INotifyPropertyChanged</code> (not shown for the sake of brevity):</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> ModelObject <span style="color: #008000;">:</span> INotifyPropertyChanged
<span style="color: #008000;">&#123;</span>
  <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">int</span> Shoesize <span style="color: #008000;">&#123;</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;">double</span> Height <span style="color: #008000;">&#123;</span><span style="color: #008000;">...</span><span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>The constructor instantiates the model object and sets it as the DataContext:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> MainPage<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
  InitializeComponent<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
  var model <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> ModelObject<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
  <span style="color: #008000;">&#123;</span>
    Shoesize <span style="color: #008000;">=</span> <span style="color: #FF0000;">12</span>,
    Height <span style="color: #008000;">=</span> <span style="color: #FF0000;">34.5</span>
  <span style="color: #008000;">&#125;</span><span style="color: #008000;">;</span>
&nbsp;
  <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">DataContext</span> <span style="color: #008000;">=</span> model<span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>This produces the expected behaviour, a label and a text field that allows you to edit the Shoesize property:</p>
<p><img src="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2012/02/Userinterface.png" alt="" title="Userinterface" width="306" height="39" class="aligncenter size-full wp-image-1964" /></p>
<p>Let’s say we want to allow the user to edit the Height property as well. We could cut and paste our current XAML, but this will only cause maintenance issues in future. Instead, the preferred approach would be to move the XAML into a user control, allowing it to be re-used.</p>
<p>The first step is to create a new user control, <code>FieldUserControl</code>, and move our XAML into there:</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;UserControl</span> <span style="color: #000066;">x:Class</span>=<span style="color: #ff0000;">&quot;UserControlExample.FieldUserControl&quot;</span></span>
<span style="color: #009900;">    ...<span style="color: #000000; font-weight: bold;">&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;StackPanel</span> <span style="color: #000066;">Orientation</span>=<span style="color: #ff0000;">&quot;Horizontal&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;TextBlock</span> <span style="color: #000066;">Text</span>=<span style="color: #ff0000;">&quot;Shoesize:&quot;</span></span>
<span style="color: #009900;">               <span style="color: #000066;">Width</span>=<span style="color: #ff0000;">&quot;100&quot;</span></span>
<span style="color: #009900;">               <span style="color: #000066;">VerticalAlignment</span>=<span style="color: #ff0000;">&quot;Center&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;">Text</span>=<span style="color: #ff0000;">&quot;{Binding Path=Shoesize}&quot;</span></span>
<span style="color: #009900;">             <span style="color: #000066;">Width</span>=<span style="color: #ff0000;">&quot;100&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/StackPanel<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/UserControl<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>We can now replace the XAML we have moved with an instance of this user control:</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;UserControl</span> <span style="color: #000066;">x:Class</span>=<span style="color: #ff0000;">&quot;UserControlExample.MainPage&quot;</span></span>
<span style="color: #009900;">    <span style="color: #000066;">xmlns:local</span>=<span style="color: #ff0000;">&quot;clr-namespace:UserControlExample&quot;</span></span>
<span style="color: #009900;">    ...<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;LayoutRoot&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;local:FieldUserControl</span> <span style="color: #000066;">VerticalAlignment</span>=<span style="color: #ff0000;">&quot;Top&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;/UserControl<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Compiling and running this code proves that this still works; we can see the model property and edit it:</p>
<p><img src="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2012/02/Userinterface.png" alt="" title="Userinterface" width="306" height="39" class="aligncenter size-full wp-image-1964" /></p>
<p>For trivial user controls this is all we need to do. However, in most cases, like this one, you will find that there are some elements of your user control that you wish to configure. In order to use this control for editing the <code>Height </code>property we need to make the label configurable. We do this by adding a Label property to our <code>FieldUserControl</code>.</p>
<p>This is where things get a bit tricky! Ideally this property should support binding, just like any other property of the framework UI controls. The WPF / Silverlight binding framework revolves around the concept of dependency properties, you can make any property the source of a binding, but the target must be a dependency property (DP). So let’s go ahead and add a <code>Label</code> dependency property to our user control:</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;">partial</span> <span style="color: #6666cc; font-weight: bold;">class</span> FieldUserControl <span style="color: #008000;">:</span> UserControl
<span style="color: #008000;">&#123;</span>
  <span style="color: #008080;">#region Label DP</span>
&nbsp;
  <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
  <span style="color: #008080; font-style: italic;">/// Gets or sets the Label which is displayed next to the field</span>
  <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
  <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">String</span> Label
  <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: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">String</span><span style="color: #008000;">&#41;</span>GetValue<span style="color: #008000;">&#40;</span>LabelProperty<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
    set <span style="color: #008000;">&#123;</span> SetValue<span style="color: #008000;">&#40;</span>LabelProperty, value<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: #008080; font-style: italic;">/// &lt;summary&gt;</span>
  <span style="color: #008080; font-style: italic;">/// Identified the Label dependency property</span>
  <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
  <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 LabelProperty <span style="color: #008000;">=</span>
      DependencyProperty<span style="color: #008000;">.</span><span style="color: #0000FF;">Register</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Label&quot;</span>, <span style="color: #008000;">typeof</span><span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&#41;</span>,
        <span style="color: #008000;">typeof</span><span style="color: #008000;">&#40;</span>FieldUserControl<span style="color: #008000;">&#41;</span>, <span style="color: #008000;">new</span> PropertyMetadata<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;&quot;</span><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: #0600FF; font-weight: bold;">public</span> FieldUserControl<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
  <span style="color: #008000;">&#123;</span>
    InitializeComponent<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>A lot of code isn’t it? It’s all boiler-plate stuff, you just have to live with it (I’d recommend either using code-snippets, or <a href="http://www.scottlogic.co.uk/blog/colin/2009/08/declarative-dependency-property-definition-with-t4-dte/">code generation for DPs</a>) </p>
<p>We can now go ahead and bind the label text to this 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;UserControl</span> <span style="color: #000066;">x:Class</span>=<span style="color: #ff0000;">&quot;UserControlExample.FieldUserControl&quot;</span></span>
<span style="color: #009900;">    ...<span style="color: #000000; font-weight: bold;">&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;StackPanel</span> <span style="color: #000066;">Orientation</span>=<span style="color: #ff0000;">&quot;Horizontal&quot;</span> <span style="color: #000066;">x:Name</span>=<span style="color: #ff0000;">&quot;LayoutRoot&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;TextBlock</span> <span style="color: #000066;">Text</span>=<span style="color: #ff0000;">&quot;{Binding Path=Label}&quot;</span></span>
<span style="color: #009900;">               <span style="color: #000066;">Width</span>=<span style="color: #ff0000;">&quot;100&quot;</span></span>
<span style="color: #009900;">               <span style="color: #000066;">VerticalAlignment</span>=<span style="color: #ff0000;">&quot;Center&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;">Text</span>=<span style="color: #ff0000;">&quot;{Binding Path=Shoesize}&quot;</span></span>
<span style="color: #009900;">             <span style="color: #000066;">Width</span>=<span style="color: #ff0000;">&quot;100&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/StackPanel<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/UserControl<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>However, if you compile and run the above code, you’ll find that it doesn’t work. The model property value is still displayed but the label is not.</p>
<p><img src="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2012/02/NoLabel.png" alt="" title="NoLabel" width="281" height="30" class="aligncenter size-full wp-image-1962" /></p>
<p>So why is this?</p>
<p>Bindings have both a source and a target; where the binding framework is responsible for handling change notifications from the source and (optionally) the target, keeping the two synchronized. The bindings in our <code>FieldUserControl </code>have a value for the Path, which specifies the target, but what is the source?</p>
<p>If you create a binding in XAML but do not specify the source (which is probably the most common use case), the source will be set to the <code>DataContext </code>of the control the binding has been specified on. The DataContext is inherited down the visual tree, from each control’s parent to child. The <code>DataContext </code>is most often set to a view model or business / model object, as in our case where the top level control, the <code>MainPage</code>, has its <code>DataContext</code> set to an instance of <code>ModelObject</code>.</p>
<p>As a result, the <code>DataContext </code>for <code>FieldUserControl </code>and all of its child elements is also <code>ModelObject</code>. This is why our Value binding is failing. Value is a property of <code>FieldUserControl</code>, not our model object.</p>
<p>So how do we go about fixing this? Most people’s first reaction is to set the <code>DataContext </code>of the user control to itself (I distinctly recall doing this myself the first time I encountered this problem!). We’ll find out later that this is a mistake – but for now let’s just go with it!</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> FieldUserControl<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
  InitializeComponent<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;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">DataContext</span> <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>With the <code>DataContext</code> of the control now set to itself, our label is now working:</p>
<p><img src="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2012/02/NoValue.png" alt="" title="NoValue" width="293" height="34" class="aligncenter size-full wp-image-1963" /></p>
<p>However, now our value has disappeared! Again, this is a <code>DataContext </code>issue, the binding in our user control is on a <code>Shoesize </code>property, whilst the <code>DataContext</code> is now the <code>FieldUserControl </code>instance.</p>
<p>This is not such a big problem, we were going to have to change that anyway, a hard-coded binding to the <code>Shoesize</code> property means that we cannot re-use this control to edit other properties of the model object.</p>
<p>So we add another dependency property to our user control. We already have the <code>Label </code>dependency property, we now add a <code>Value</code> property:</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;">partial</span> <span style="color: #6666cc; font-weight: bold;">class</span> FieldUserControl <span style="color: #008000;">:</span> UserControl
<span style="color: #008000;">&#123;</span>
  <span style="color: #008080;">#region Label DP</span>
&nbsp;
  <span style="color: #008000;">...</span>
&nbsp;
  <span style="color: #008080;">#endregion</span>
&nbsp;
  <span style="color: #008080;">#region Value DP</span>
&nbsp;
  <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
  <span style="color: #008080; font-style: italic;">/// Gets or sets the Value which is being displayed</span>
  <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
  <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> <span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">object</span><span style="color: #008000;">&#41;</span>GetValue<span style="color: #008000;">&#40;</span>ValueProperty<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
    set <span style="color: #008000;">&#123;</span> SetValue<span style="color: #008000;">&#40;</span>ValueProperty, value<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: #008080; font-style: italic;">/// &lt;summary&gt;</span>
  <span style="color: #008080; font-style: italic;">/// Identified the Label dependency property</span>
  <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
  <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 ValueProperty <span style="color: #008000;">=</span>
      DependencyProperty<span style="color: #008000;">.</span><span style="color: #0000FF;">Register</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Value&quot;</span>, <span style="color: #008000;">typeof</span><span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">object</span><span style="color: #008000;">&#41;</span>,
        <span style="color: #008000;">typeof</span><span style="color: #008000;">&#40;</span>FieldUserControl<span style="color: #008000;">&#41;</span>, <span style="color: #008000;">new</span> PropertyMetadata<span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">null</span><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: #0600FF; font-weight: bold;">public</span> FieldUserControl<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
  <span style="color: #008000;">&#123;</span>
    InitializeComponent<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;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">DataContext</span> <span style="color: #008000;">=</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></pre></div></div>

<p>This value property is bound to the user control UI 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;UserControl</span> <span style="color: #000066;">x:Class</span>=<span style="color: #ff0000;">&quot;UserControlExample.FieldUserControl&quot;</span></span>
<span style="color: #009900;">    ...<span style="color: #000000; font-weight: bold;">&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;StackPanel</span> <span style="color: #000066;">Orientation</span>=<span style="color: #ff0000;">&quot;Horizontal&quot;</span> <span style="color: #000066;">x:Name</span>=<span style="color: #ff0000;">&quot;LayoutRoot&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;TextBlock</span> <span style="color: #000066;">Text</span>=<span style="color: #ff0000;">&quot;{Binding Path=Label}&quot;</span></span>
<span style="color: #009900;">               <span style="color: #000066;">Width</span>=<span style="color: #ff0000;">&quot;100&quot;</span></span>
<span style="color: #009900;">               <span style="color: #000066;">VerticalAlignment</span>=<span style="color: #ff0000;">&quot;Center&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;">Text</span>=<span style="color: #ff0000;">&quot;{Binding Path=Value}&quot;</span></span>
<span style="color: #009900;">             <span style="color: #000066;">Width</span>=<span style="color: #ff0000;">&quot;100&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/StackPanel<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/UserControl<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>The idea here is that the exposed <code>Value</code> property ‘relays’ the value of the binding in our<code> MainPage.xaml</code>, which now has a binding which tells us which model object property is being displayed in our user control:</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;Grid<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;StackPanel</span> <span style="color: #000066;">Orientation</span>=<span style="color: #ff0000;">&quot;Vertical&quot;</span></span>
<span style="color: #009900;">              <span style="color: #000066;">HorizontalAlignment</span>=<span style="color: #ff0000;">&quot;Left&quot;</span></span>
<span style="color: #009900;">              <span style="color: #000066;">Margin</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;local:FieldUserControl</span> <span style="color: #000066;">VerticalAlignment</span>=<span style="color: #ff0000;">&quot;Top&quot;</span></span>
<span style="color: #009900;">                            <span style="color: #000066;">Label</span>=<span style="color: #ff0000;">&quot;Height:&quot;</span></span>
<span style="color: #009900;">                            <span style="color: #000066;">Value</span>=<span style="color: #ff0000;">&quot;{Binding Height}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;local:FieldUserControl</span> <span style="color: #000066;">VerticalAlignment</span>=<span style="color: #ff0000;">&quot;Top&quot;</span></span>
<span style="color: #009900;">                            <span style="color: #000066;">Label</span>=<span style="color: #ff0000;">&quot;Shoesize:&quot;</span></span>
<span style="color: #009900;">                            <span style="color: #000066;">Value</span>=<span style="color: #ff0000;">&quot;{Binding Height}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/StackPanel<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></pre></div></div>

<p>If you compile and run this code you will find that … it doesn’t work!</p>
<p><img src="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2012/02/NoValue.png" alt="" title="NoValue" width="293" height="34" class="aligncenter size-full wp-image-1963" /></p>
<p>Remember earlier when I said that setting the user control’s <code>DataContext</code> to itself is a mistake? We have just found out why!</p>
<p>The source of a binding is the <code>DataContext </code>of the control it is defined upon. In our <code>MainPage.xaml</code> we have attempted to bind the <code>Value </code>property of the <code>FieldUserControl </code>to the <code>Height </code>property on our model object. However, the code within the <code>FieldUserControl</code> constructor means that it no longer inherits its parent’s <code>DataContext </code>(i.e. our model object), so this binding does not work.</p>
<p>This problem can be fixed by setting the <code>DataContext </code>of the <code>FieldUserControl</code>’s root element to itself.</p>
<p>Note that the user control has a StackPanel as its root element and that this is named <code>LayoutRoot</code>:</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;UserControl</span> <span style="color: #000066;">x:Class</span>=<span style="color: #ff0000;">&quot;UserControlExample.FieldUserControl&quot;</span></span>
<span style="color: #009900;">    ...<span style="color: #000000; font-weight: bold;">&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;StackPanel</span> <span style="color: #000066;">Orientation</span>=<span style="color: #ff0000;">&quot;Horizontal&quot;</span></span>
<span style="color: #009900;">              <span style="color: #000066;">x:Name</span>=<span style="color: #ff0000;">&quot;LayoutRoot&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    ...
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/StackPanel<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/UserControl<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>We change the constructor so that it sets the <code>LayoutRoot </code><code>DataContext </code>to 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> FieldUserControl<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
  InitializeComponent<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;">//this.DataContext = this;</span>
  LayoutRoot<span style="color: #008000;">.</span><span style="color: #0000FF;">DataContext</span> <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>This means that the <code>FieldUserControl </code>still inherits its parent’s <code>DataContext</code>, so bindings to our model object will work. Furthermore, the <code>FieldUserControl </code>and its children all have the <code>FieldUserControl </code>as their <code>DataContext</code>, so their bindings work also:</p>
<p><img src="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2012/02/ItWorks.png" alt="" title="ItWorks" width="269" height="36" class="aligncenter size-full wp-image-1961" /></p>
<p>Finally, we’re done!</p>
<p>If the technique of binding the layout root of the user control to itself is a bit confusing &#8211; the following diagram, which shows the visual tree of our simple application, might help:</p>
<p><img src="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2012/02/DataContext.png" alt="" title="DataContext" width="550" height="377" class="aligncenter size-full wp-image-1959" /></p>
<p>Again, notice that the <code>DataContext </code>of <code>FieldUserControl </code>is inherited from its parent. This means that any bindings we add to <code>FieldUserControl</code> have the <code>ModelObect </code>as their source.</p>
<p>We can now create multiple instances of <code>FieldUserControl </code>to edit different properties:</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;UserControl</span> <span style="color: #000066;">x:Class</span>=<span style="color: #ff0000;">&quot;UserControlExample.MainPage&quot;</span></span>
<span style="color: #009900;">    <span style="color: #000066;">xmlns:local</span>=<span style="color: #ff0000;">&quot;clr-namespace:UserControlExample&quot;</span></span>
<span style="color: #009900;">    ...<span style="color: #000000; font-weight: bold;">&gt;</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;StackPanel</span> <span style="color: #000066;">Orientation</span>=<span style="color: #ff0000;">&quot;Vertical&quot;</span></span>
<span style="color: #009900;">                <span style="color: #000066;">HorizontalAlignment</span>=<span style="color: #ff0000;">&quot;Left&quot;</span></span>
<span style="color: #009900;">                <span style="color: #000066;">Margin</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;local:FieldUserControl</span> <span style="color: #000066;">VerticalAlignment</span>=<span style="color: #ff0000;">&quot;Top&quot;</span></span>
<span style="color: #009900;">                              <span style="color: #000066;">Label</span>=<span style="color: #ff0000;">&quot;Height:&quot;</span></span>
<span style="color: #009900;">                              <span style="color: #000066;">Value</span>=<span style="color: #ff0000;">&quot;{Binding Height}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;local:FieldUserControl</span> <span style="color: #000066;">VerticalAlignment</span>=<span style="color: #ff0000;">&quot;Top&quot;</span></span>
<span style="color: #009900;">                              <span style="color: #000066;">Label</span>=<span style="color: #ff0000;">&quot;Shoesize:&quot;</span></span>
<span style="color: #009900;">                              <span style="color: #000066;">Value</span>=<span style="color: #ff0000;">&quot;{Binding 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;/StackPanel<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;/UserControl<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>With an update of the <code>FieldUserControl</code> styling, the result looks like this:</p>
<p><img src="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2012/02/final.png" alt="" title="final" width="232" height="77" class="aligncenter size-full wp-image-1960" /></p>
<p>We now have a truly re-useable user control!</p>
<p>As an aside, for bonus points, you can bind the layout root <code>DataContext</code> without any code-behind by using an <code>ElementName</code> binding 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;UserControl</span> <span style="color: #000066;">x:Class</span>=<span style="color: #ff0000;">&quot;UserControlExample.FieldUserControl&quot;</span></span>
<span style="color: #009900;">             <span style="color: #000066;">x:Name</span>=<span style="color: #ff0000;">&quot;parent&quot;</span> ...<span style="color: #000000; font-weight: bold;">&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;StackPanel</span> <span style="color: #000066;">Orientation</span>=<span style="color: #ff0000;">&quot;Horizontal&quot;</span></span>
<span style="color: #009900;">              <span style="color: #000066;">DataContext</span>=<span style="color: #ff0000;">&quot;{Binding ElementName=parent}&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;TextBlock</span> <span style="color: #000066;">Text</span>=<span style="color: #ff0000;">&quot;{Binding Path=Label}&quot;</span></span>
<span style="color: #009900;">               <span style="color: #000066;">Width</span>=<span style="color: #ff0000;">&quot;100&quot;</span></span>
<span style="color: #009900;">               <span style="color: #000066;">VerticalAlignment</span>=<span style="color: #ff0000;">&quot;Center&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;">Text</span>=<span style="color: #ff0000;">&quot;{Binding Path=Shoesize}&quot;</span></span>
<span style="color: #009900;">             <span style="color: #000066;">Width</span>=<span style="color: #ff0000;">&quot;100&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/StackPanel<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/UserControl<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Or, in WPF you could event use a<code> RelativeSource FindAncestor</code> binding, with <code>AncestorType </code>set to the type of <code>FieldUserControl </code>(but that would just be showing off!).</p>
<p>Hopefully this blog post will help anyone who is confused about how to create user controls which expose properties in WPF or Silverlight.</p>
<p>You can download the sourcecode for the example: <a href='http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2012/02/UserControlExample.zip'>UserControlExample.zip</a></p>
<p>Regards, Colin E.</p>

]]></content:encoded>
			<wfw:commentRss>http://www.scottlogic.co.uk/blog/colin/2012/02/a-simple-pattern-for-creating-re-useable-usercontrols-in-wpf-silverlight/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Using a Grid as the Panel for an ItemsControl</title>
		<link>http://www.scottlogic.co.uk/blog/colin/2010/11/using-a-grid-as-the-panel-for-an-itemscontrol/</link>
		<comments>http://www.scottlogic.co.uk/blog/colin/2010/11/using-a-grid-as-the-panel-for-an-itemscontrol/#comments</comments>
		<pubDate>Mon, 15 Nov 2010 08:31:03 +0000</pubDate>
		<dc:creator>Colin Eberhardt</dc:creator>
				<category><![CDATA[codeproject]]></category>
		<category><![CDATA[binding]]></category>
		<category><![CDATA[ItemsControl]]></category>

		<guid isPermaLink="false">http://www.scottlogic.co.uk/blog/colin/?p=927</guid>
		<description><![CDATA[In this blog post I look at how to use a Grid as the ItemsPanel for an ItemsControl, solving a few of the issues that crop up along the way. The Grid is probably the most useful of Silverlight and WPF’s panels (panels are elements which provide a mechanism for laying out their children). 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%252F2010%252F11%252Fusing-a-grid-as-the-panel-for-an-itemscontrol%252F%22%2C%20%22style%22%3A%20%22big%22%2C%20%22title%22%3A%20%22Using%20a%20Grid%20as%20the%20Panel%20for%20an%20ItemsControl%20%23%22%20%7D);"></div>
<p><i>In this blog post I look at how to use a Grid as the ItemsPanel for an ItemsControl, solving a few of the issues that crop up along the way.</i></p>
<p>The Grid is probably the most useful of Silverlight and WPF’s panels (panels are elements which provide a mechanism for laying out their children). The ItemsControl provides a mechanism for generating multiple instances of some template based on the data that is bound to it. The ItemsControl ‘concept’ is highlight versatile, and is used as the foundation for many of the framework controls, I find myself using it all the time.</p>
<p>Isn’t it a shame that Grid and ItemsControl don’t play together nicely?	</p>
<p>So what do I mean by this? I am sure that if you have ever tried to generate Grid a layout using an ItemsControl you will know what I am talking about, but if not, here’s a very brief summary of the problem. An ItemsControl manages a number of child elements, you can configure the type of panel the ItemsControl adds children to via its ItemsPanel property. If I have a list of strings which I want to render using a Grid, I might expect the following to work &#8230; in 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;ItemsControl</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: #808080; font-style: italic;">&lt;!-- host the items generated by this ItemsControl in a grid --&gt;</span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ItemsControl.ItemsPanel<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ItemsPanelTemplate<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><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/ItemsPanelTemplate<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/ItemsControl.ItemsPanel<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #808080; font-style: italic;">&lt;!-- render each bound item using a TextBlock--&gt;</span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ItemsControl.ItemTemplate<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;TextBlock</span> <span style="color: #000066;">Text</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;/DataTemplate<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/ItemsControl.ItemTemplate<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/ItemsControl<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>And in code-behind:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">DataContext</span> <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> <span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span>
  <span style="color: #008000;">&#123;</span> <span style="color: #666666;">&quot;one&quot;</span>, <span style="color: #666666;">&quot;two&quot;</span>, <span style="color: #666666;">&quot;three&quot;</span>, <span style="color: #666666;">&quot;four&quot;</span>, <span style="color: #666666;">&quot;five&quot;</span>  <span style="color: #008000;">&#125;</span><span style="color: #008000;">;</span></pre></div></div>

<p>So what is wrong with the above? There are a couple of problems:</p>
<ol>
<li>When using a Grid you must add the required number of rows / columns via the RowDefinitions ColumnDefinitions properties. In the above example what we really want is for the grid rows to be added dynamically based on the number of items in the bound data. Unfortunately this is not supported either by the Grid or the ItemsControl.</li>
<li>The second problem is that items within a grid must declare the row / column that they occupy via the Grid.Row and Grid.Column attached properties. You might think that you could add a Grid.Row property to the TextBlock in the above example, binding it to some other property of the bound collection. However, this will not work because the TextBlock elements are not added into the grid directly; each one is added as the content of a ContentPresenter which is generated for us.</li>
</ol>
<p>The above two problems mean that it is not possible to use a Grid as the panel within an ItemsControl. In this blog post I will show a solution to these problems &#8230;</p>
<h2>Dynamically adding RowDefinitions</h2>
<p>The first problem to overcome is how to dynamically add the required number of RowDefinitions to our Grid. To support this I added an attached property ItemsPerRow, which upon attachment handles the LayoutUpdated event. This event is fired when items are added to the grid, this enables us to compute the number of RowDefinitions that are required, and also to assign a row index to each of the Grid’s children. The following code is the property changed handler for the attached ItemsPerRow property:</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;">/// Handles property changed event for the ItemsPerRow property, constructing</span>
<span style="color: #008080; font-style: italic;">/// the required ItemsPerRow elements on the grid which this property is attached to.</span>
<span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</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> OnItemsPerRowPropertyChanged<span style="color: #008000;">&#40;</span>DependencyObject d,
                    DependencyPropertyChangedEventArgs e<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
  Grid grid <span style="color: #008000;">=</span> d <span style="color: #0600FF; font-weight: bold;">as</span> Grid<span style="color: #008000;">;</span>
  <span style="color: #6666cc; font-weight: bold;">int</span> itemsPerRow <span style="color: #008000;">=</span> <span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">int</span><span style="color: #008000;">&#41;</span>e<span style="color: #008000;">.</span><span style="color: #0000FF;">NewValue</span><span style="color: #008000;">;</span>
&nbsp;
  <span style="color: #008080; font-style: italic;">// construct the required row definitions</span>
  grid<span style="color: #008000;">.</span><span style="color: #0000FF;">LayoutUpdated</span> <span style="color: #008000;">+=</span> <span style="color: #008000;">&#40;</span>s, e2<span style="color: #008000;">&#41;</span> <span style="color: #008000;">=&gt;</span>
    <span style="color: #008000;">&#123;</span>
      var childCount <span style="color: #008000;">=</span> grid<span style="color: #008000;">.</span><span style="color: #0000FF;">Children</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Count</span><span style="color: #008000;">;</span>
&nbsp;
      <span style="color: #008080; font-style: italic;">// add the required number of row definitions</span>
      <span style="color: #6666cc; font-weight: bold;">int</span> rowsToAdd <span style="color: #008000;">=</span> <span style="color: #008000;">&#40;</span>childCount <span style="color: #008000;">-</span> grid<span style="color: #008000;">.</span><span style="color: #0000FF;">RowDefinitions</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Count</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">/</span> itemsPerRow<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> row <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span> row <span style="color: #008000;">&lt;</span> rowsToAdd<span style="color: #008000;">;</span> row<span style="color: #008000;">++</span><span style="color: #008000;">&#41;</span>
      <span style="color: #008000;">&#123;</span>
        grid<span style="color: #008000;">.</span><span style="color: #0000FF;">RowDefinitions</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Add</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">new</span> RowDefinition<span style="color: #008000;">&#40;</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: #008080; font-style: italic;">// set the row property for each chid</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> childCount<span style="color: #008000;">;</span> i<span style="color: #008000;">++</span><span style="color: #008000;">&#41;</span>
      <span style="color: #008000;">&#123;</span>
        var child <span style="color: #008000;">=</span> grid<span style="color: #008000;">.</span><span style="color: #0000FF;">Children</span><span style="color: #008000;">&#91;</span>i<span style="color: #008000;">&#93;</span> <span style="color: #0600FF; font-weight: bold;">as</span> FrameworkElement<span style="color: #008000;">;</span>
        Grid<span style="color: #008000;">.</span><span style="color: #0000FF;">SetRow</span><span style="color: #008000;">&#40;</span>child, i <span style="color: #008000;">/</span> itemsPerRow<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;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Note the use of a lambda expression for the event handler in order to ‘capture’ a reference to the Grid (as described in my previous blog post on <a href="http://www.scottlogic.co.uk/blog/colin/2010/07/exposing-and-binding-to-a-silverlight-scrollviewer%E2%80%99s-scrollbars/">binding the ScrollViewers offset properties</a>).</p>
<p>Changing our markup to use the above attached 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;ItemsControl</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;ItemsControl.ItemsPanel<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ItemsPanelTemplate<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #808080; font-style: italic;">&lt;!-- use the ItemsPerRow attached property to dynamically add rows --&gt;</span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Grid</span> <span style="color: #000066;">local:GridUtils.ItemsPerRow</span>=<span style="color: #ff0000;">&quot;1&quot;</span></span>
<span style="color: #009900;">          <span style="color: #000066;">ShowGridLines</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;/ItemsPanelTemplate<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/ItemsControl.ItemsPanel<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ItemsControl.ItemTemplate<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;TextBlock</span> <span style="color: #000066;">Text</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;/DataTemplate<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/ItemsControl.ItemTemplate<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/ItemsControl<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>The array of strings bound in code-behind results in the following grid layout being rendered:</p>
<p><img src="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2010/11/gridOne.png" alt="" title="gridOne" width="105" height="93" class="aligncenter size-full wp-image-928" /></p>
<p>Great, all fixed. Time to grab a coffee.</p>
<p>Unfortunately it isn’t that simple. The above example has a single item per grid row, typically you would want to have multiple items in each row, with each item positioned in a different column. This is where it gets tricky. DataTemplate only supports a single child element, so we will have to wrap the elements which we want to add into our grid in a panel of some sort. However, if we do this, the column index that we apply to the element of each row will be ignored because the Grid only honours the Row and Column properties of its direct descendants.</p>
<h2>Creating a Row Template</h2>
<p>In order to circumnavigate this issue, I have created a ‘phantom’ panel, which hosts the elements that are added to each grid row. When a phantom panel is added to the grid, its children are removed and added to the grid and the phantom is destroyed.</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> PhantomPanel <span style="color: #008000;">:</span> Panel
<span style="color: #008000;">&#123;</span>
&nbsp;
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>The property changed handler shown above is extended to remove this phantom:</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: #0600FF; font-weight: bold;">static</span> <span style="color: #6666cc; font-weight: bold;">void</span> OnItemsPerRowPropertyChanged<span style="color: #008000;">&#40;</span>DependencyObject d,
                    DependencyPropertyChangedEventArgs e<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
  Grid grid <span style="color: #008000;">=</span> d <span style="color: #0600FF; font-weight: bold;">as</span> Grid<span style="color: #008000;">;</span>
  <span style="color: #6666cc; font-weight: bold;">int</span> itemsPerRow <span style="color: #008000;">=</span> <span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">int</span><span style="color: #008000;">&#41;</span>e<span style="color: #008000;">.</span><span style="color: #0000FF;">NewValue</span><span style="color: #008000;">;</span>
&nbsp;
  <span style="color: #008080; font-style: italic;">// construct the required row definitions</span>
  grid<span style="color: #008000;">.</span><span style="color: #0000FF;">LayoutUpdated</span> <span style="color: #008000;">+=</span> <span style="color: #008000;">&#40;</span>s, e2<span style="color: #008000;">&#41;</span> <span style="color: #008000;">=&gt;</span>
    <span style="color: #008000;">&#123;</span>
      <span style="color: #008080; font-style: italic;">// iterate over any new content presenters (i.e. instances of our DataTemplate)</span>
      <span style="color: #008080; font-style: italic;">// that have been added to the grid</span>
      var presenters <span style="color: #008000;">=</span> grid<span style="color: #008000;">.</span><span style="color: #0000FF;">Children</span><span style="color: #008000;">.</span><span style="color: #0000FF;">OfType</span><span style="color: #008000;">&lt;</span>ContentPresenter<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: #0000FF;">ToList</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;">foreach</span> <span style="color: #008000;">&#40;</span>var presenter <span style="color: #0600FF; font-weight: bold;">in</span> presenters<span style="color: #008000;">&#41;</span>
      <span style="color: #008000;">&#123;</span>
        <span style="color: #008080; font-style: italic;">// the child of each DataTemplate should be our 'phantom' panel</span>
        var phantom <span style="color: #008000;">=</span> VisualTreeHelper<span style="color: #008000;">.</span><span style="color: #0000FF;">GetChild</span><span style="color: #008000;">&#40;</span>presenter, <span style="color: #FF0000;">0</span><span style="color: #008000;">&#41;</span> <span style="color: #0600FF; font-weight: bold;">as</span> PhantomPanel<span style="color: #008000;">;</span>
        <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>phantom <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>
&nbsp;
          <span style="color: #008080; font-style: italic;">// remove each of the children of the phantom and add to the grid</span>
          <span style="color: #0600FF; font-weight: bold;">foreach</span> <span style="color: #008000;">&#40;</span>FrameworkElement child <span style="color: #0600FF; font-weight: bold;">in</span> phantom<span style="color: #008000;">.</span><span style="color: #0000FF;">Children</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;">&#41;</span>
          <span style="color: #008000;">&#123;</span>
            phantom<span style="color: #008000;">.</span><span style="color: #0000FF;">Children</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Remove</span><span style="color: #008000;">&#40;</span>child<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            grid<span style="color: #008000;">.</span><span style="color: #0000FF;">Children</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Add</span><span style="color: #008000;">&#40;</span>child<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #008080; font-style: italic;">// ensure the child maintains its original datacontext</span>
            child<span style="color: #008000;">.</span><span style="color: #0000FF;">DataContext</span> <span style="color: #008000;">=</span> phantom<span style="color: #008000;">.</span><span style="color: #0000FF;">DataContext</span><span style="color: #008000;">;</span>
          <span style="color: #008000;">&#125;</span>
&nbsp;
          <span style="color: #008080; font-style: italic;">// remove the presenter (and phantom)</span>
          grid<span style="color: #008000;">.</span><span style="color: #0000FF;">Children</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Remove</span><span style="color: #008000;">&#40;</span>presenter<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
      <span style="color: #008000;">&#125;</span>
&nbsp;
      var childCount <span style="color: #008000;">=</span> grid<span style="color: #008000;">.</span><span style="color: #0000FF;">Children</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Count</span><span style="color: #008000;">;</span>
      <span style="color: #6666cc; font-weight: bold;">int</span> rowDifference <span style="color: #008000;">=</span> <span style="color: #008000;">&#40;</span>childCount <span style="color: #008000;">/</span> itemsPerRow<span style="color: #008000;">&#41;</span> <span style="color: #008000;">-</span> grid<span style="color: #008000;">.</span><span style="color: #0000FF;">RowDefinitions</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Count</span><span style="color: #008000;">;</span>
&nbsp;
      <span style="color: #008080; font-style: italic;">// if new items have been added, create the required grid rows</span>
      <span style="color: #008080; font-style: italic;">// and assign the row index to each child</span>
      <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>rowDifference <span style="color: #008000;">!=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">&#41;</span>
      <span style="color: #008000;">&#123;</span>
        grid<span style="color: #008000;">.</span><span style="color: #0000FF;">RowDefinitions</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>
        <span style="color: #0600FF; font-weight: bold;">for</span> <span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">int</span> row <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span> row <span style="color: #008000;">&lt;</span> <span style="color: #008000;">&#40;</span>childCount <span style="color: #008000;">/</span> itemsPerRow<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span> row<span style="color: #008000;">++</span><span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
          grid<span style="color: #008000;">.</span><span style="color: #0000FF;">RowDefinitions</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Add</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">new</span> RowDefinition<span style="color: #008000;">&#40;</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: #008080; font-style: italic;">// set the row property for each chid</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> childCount<span style="color: #008000;">;</span> i<span style="color: #008000;">++</span><span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
          var child <span style="color: #008000;">=</span> grid<span style="color: #008000;">.</span><span style="color: #0000FF;">Children</span><span style="color: #008000;">&#91;</span>i<span style="color: #008000;">&#93;</span> <span style="color: #0600FF; font-weight: bold;">as</span> FrameworkElement<span style="color: #008000;">;</span>
          Grid<span style="color: #008000;">.</span><span style="color: #0000FF;">SetRow</span><span style="color: #008000;">&#40;</span>child, i <span style="color: #008000;">/</span> itemsPerRow<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><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>The above code is pretty straightforward, however there is one subtlety, we must ensure that the DataContext of each child element is set to the DataContext that the ItemsControl assigned to each PhantomPanel, i.e. the individual items that are bound to the Grid.</p>
<p>With the above code it is now possible to create a more complex grid layout:</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;StackPanel</span> <span style="color: #000066;">Orientation</span>=<span style="color: #ff0000;">&quot;Vertical&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;sdk:DataGrid</span> <span style="color: #000066;">ItemsSource</span>=<span style="color: #ff0000;">&quot;{Binding}&quot;</span> <span style="color: #000066;">Margin</span>=<span style="color: #ff0000;">&quot;10&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;">x:Name</span>=<span style="color: #ff0000;">&quot;LayoutRoot&quot;</span> <span style="color: #000066;">Background</span>=<span style="color: #ff0000;">&quot;White&quot;</span></span>
<span style="color: #009900;">        <span style="color: #000066;">BorderBrush</span>=<span style="color: #ff0000;">&quot;Black&quot;</span> <span style="color: #000066;">BorderThickness</span>=<span style="color: #ff0000;">&quot;1&quot;</span> <span style="color: #000066;">Margin</span>=<span style="color: #ff0000;">&quot;10&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;ItemsControl</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;ItemsControl.ItemsPanel<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ItemsPanelTemplate<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> <span style="color: #000066;">local:GridUtils.ItemsPerRow</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;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: #000000; font-weight: bold;">/&gt;</span></span>
              <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ColumnDefinition</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;/Grid<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/ItemsPanelTemplate<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/ItemsControl.ItemsPanel<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ItemsControl.ItemTemplate<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: #808080; font-style: italic;">&lt;!-- the row ‘template’ within a phantom panel --&gt;</span>
          <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;local:PhantomPanel<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;TextBlock</span> <span style="color: #000066;">Text</span>=<span style="color: #ff0000;">&quot;{Binding Path=Item}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;TextBlock</span> <span style="color: #000066;">Text</span>=<span style="color: #ff0000;">&quot;{Binding Path=Quantity}&quot;</span> <span style="color: #000066;">Grid.Column</span>=<span style="color: #ff0000;">&quot;1&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
          <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/local:PhantomPanel<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;/ItemsControl.ItemTemplate<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/ItemsControl<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
  <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;/StackPanel<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>The above XAML renders a list of simple model objects that implement INotifyPropertyChanged in a DataGrid and an ItemsControl (using our Grid layout). Notice that if you edit the properties of the bound objects via the DataGrid, these changes are reflected in the Grid below, i.e. it is all working!</p>
<div style="text-align: center; "><object width="300" height="240" 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/11/ItemsControlGrid.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>
<h2>Handling CollectionChanged Events</h2>
<p>The above example looks pretty complete, however there is one remaining issue, handling changes to the bound collection. The problem with the above solution is that it effectively subverts the ItemsControls usage of the ItemsPanel. The ItemsControl will expect that items that it adds to the Panel to appear at certain indices, by removing our phantom panels and adding their contente directly this is no longer the case. </p>
<p>A simple hack (and yes, it really is a hack!) is to confuse the ItemsControl into thinking that any change to our bound collection is a reset, i.e. the collection has changed completely, so the UI needs to be rebuilt from scratch. To do this, I have created an attached ItemsSource property that adapts the bound collection, ensuring that any collection changes result in the ItemsControl rebuilding its UI. The changed handler for this attached property is given below:</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;">/// Handles property changed event for the ItemsSource property.</span>
<span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</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> OnItemsSourcePropertyChanged<span style="color: #008000;">&#40;</span>DependencyObject d,
  DependencyPropertyChangedEventArgs e<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
  ItemsControl control <span style="color: #008000;">=</span> d <span style="color: #0600FF; font-weight: bold;">as</span> ItemsControl<span style="color: #008000;">;</span>
&nbsp;
  <span style="color: #008080; font-style: italic;">// set the ItemsSource of the ItemsControl that this property is attached to</span>
  control<span style="color: #008000;">.</span><span style="color: #0000FF;">ItemsSource</span> <span style="color: #008000;">=</span> e<span style="color: #008000;">.</span><span style="color: #0000FF;">NewValue</span> <span style="color: #0600FF; font-weight: bold;">as</span> IEnumerable<span style="color: #008000;">;</span>
&nbsp;
  INotifyCollectionChanged notifyCollection <span style="color: #008000;">=</span> e<span style="color: #008000;">.</span><span style="color: #0000FF;">NewValue</span> <span style="color: #0600FF; font-weight: bold;">as</span> INotifyCollectionChanged<span style="color: #008000;">;</span>
  <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>notifyCollection <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>
    <span style="color: #008080; font-style: italic;">// if a collection changed event occurs, reset the ItemsControl's</span>
    <span style="color: #008080; font-style: italic;">// ItemsSource, rebuilding the UI </span>
    notifyCollection<span style="color: #008000;">.</span><span style="color: #0000FF;">CollectionChanged</span> <span style="color: #008000;">+=</span> <span style="color: #008000;">&#40;</span>s, e2<span style="color: #008000;">&#41;</span> <span style="color: #008000;">=&gt;</span>
      <span style="color: #008000;">&#123;</span>
        control<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>
        control<span style="color: #008000;">.</span><span style="color: #0000FF;">ItemsSource</span> <span style="color: #008000;">=</span> e<span style="color: #008000;">.</span><span style="color: #0000FF;">NewValue</span> <span style="color: #0600FF; font-weight: bold;">as</span> IEnumerable<span style="color: #008000;">;</span>
      <span style="color: #008000;">&#125;</span><span style="color: #008000;">;</span>
  <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>The above attached property is used in exactly the same way as the ItemsControl.ItemsSource property which it adapts. The XAML below shows how the above attached property can be used in place of the ItemsControl 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;ItemsControl</span> <span style="color: #000066;">local:GridUtils.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;ItemsControl.ItemsPanel<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ItemsPanelTemplate<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> <span style="color: #000066;">local:GridUtils.ItemsPerRow</span>=<span style="color: #ff0000;">&quot;3&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;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;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;/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;/Grid<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/ItemsPanelTemplate<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/ItemsControl.ItemsPanel<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ItemsControl.ItemTemplate<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;local:PhantomPanel<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;TextBlock</span> <span style="color: #000066;">Text</span>=<span style="color: #ff0000;">&quot;{Binding Path=Item}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;TextBlock</span> <span style="color: #000066;">Text</span>=<span style="color: #ff0000;">&quot;{Binding Path=Quantity}&quot;</span> <span style="color: #000066;">Grid.Column</span>=<span style="color: #ff0000;">&quot;1&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Line</span> <span style="color: #000066;">Stroke</span>=<span style="color: #ff0000;">&quot;LightGray&quot;</span> <span style="color: #000066;">StrokeThickness</span>=<span style="color: #ff0000;">&quot;1&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;">X1</span>=<span style="color: #ff0000;">&quot;0&quot;</span> <span style="color: #000066;">X2</span>=<span style="color: #ff0000;">&quot;1&quot;</span> <span style="color: #000066;">Y1</span>=<span style="color: #ff0000;">&quot;0&quot;</span> <span style="color: #000066;">Y2</span>=<span style="color: #ff0000;">&quot;0&quot;</span></span>
<span style="color: #009900;">              <span style="color: #000066;">Stretch</span>=<span style="color: #ff0000;">&quot;Fill&quot;</span></span>
<span style="color: #009900;">              <span style="color: #000066;">Grid.ColumnSpan</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;/local:PhantomPanel<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;/ItemsControl.ItemTemplate<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/ItemsControl<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>And here it is with a DataGrid bound to the same data:</p>
<div style="text-align: center; "><object width="300" height="380" 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/11/ItemsControlGridTwo.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 add, remove and update the bound objects and the Grid rendered via the ItemsControl remains synchronised with the bound data.</p>
<h2>Conclusions</h2>
<p>Finally, the ItemsControl and Grid can be used together, a cause for much rejoicing! I must admit, I am pretty pleased with my solution; however, it is far from perfect. There are a couple of areas of this implementation that you should be wary of.</p>
<p>Firstly, the use of the LayoutUpdated event which we use to determine when items are added to our Grid. This event gets fired when anything changes in our visual tree’s layout. It has the potential to be called a lot, which is why I am always careful to check conditions and exit this method as quickly as possible if the UI is not in the state I am interested in.</p>
<p>Secondly, adapting the ItemsSource to force a Reset whenever an items is added or removed is pretty costly!</p>
<p>If you do not use the technique for rendering large quantities of data it will probably be just fine. It may be fine for large volumes of data also, however, it is always better to be aware of potential issue.</p>
<p>If anyone has any ideas on how to improve on this technique, please leave a comment below:</p>
<p>You can download the full project sourcecode: <a href='http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2010/11/ItemsControlGrid.zip'>ItemsControlGrid.zip</a></p>
<p>Regards, Colin E.</p>

]]></content:encoded>
			<wfw:commentRss>http://www.scottlogic.co.uk/blog/colin/2010/11/using-a-grid-as-the-panel-for-an-itemscontrol/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
		<item>
		<title>Silverlight MultiBinding updated, adding support for ElementName and TwoWay binding</title>
		<link>http://www.scottlogic.co.uk/blog/colin/2010/08/silverlight-multibinding-updated-adding-support-for-elementname-and-twoway-binding/</link>
		<comments>http://www.scottlogic.co.uk/blog/colin/2010/08/silverlight-multibinding-updated-adding-support-for-elementname-and-twoway-binding/#comments</comments>
		<pubDate>Thu, 12 Aug 2010 20:11:39 +0000</pubDate>
		<dc:creator>Colin Eberhardt</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[binding]]></category>
		<category><![CDATA[multibinding]]></category>
		<category><![CDATA[silverlight]]></category>
		<category><![CDATA[virtual branch]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://www.scottlogic.co.uk/blog/colin/?p=755</guid>
		<description><![CDATA[This blog post describes an update to the Silverlight 4 MultiBinding technique I blogged about a couple of months ago to add support for ElementName binding and TwoWay binding. A few months ago I posted an update to my MultiBinding solution for Silverlight 4. This technique allows you to perform the same kind of multibindings [...]]]></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%252F08%252Fsilverlight-multibinding-updated-adding-support-for-elementname-and-twoway-binding%252F%22%2C%20%22style%22%3A%20%22big%22%2C%20%22title%22%3A%20%22Silverlight%20MultiBinding%20updated%2C%20adding%20support%20for%20ElementName%20and%20TwoWay%20binding%20%23%22%20%7D);"></div>
<p><em>This blog post describes an update to the Silverlight 4 MultiBinding technique I blogged about a couple of months ago to add support for ElementName binding and TwoWay binding.</em></p>
<p>A few months ago I posted an update to my MultiBinding solution for Silverlight 4. This technique allows you to perform the same kind of multibindings which are possible in WPF, where a property value is bound to multiple sources via a special value converter that implements the IMultiValueConverter interface, which describes how these values are combined. This update proved popular once again, and I received a few requests to add support for ElementName and TwoWay binding. I like challenge! This blog post describes how these two features were implemented, but if you just want to grab the code, you will find the link at the end of this article.</p>
<p><strong>A brief recap</strong></p>
<p>Before I go into the implementation details for the new features I will provide a brief recap of how my multibinding solution works. The XAML for creating a multibinding 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;TextBlock</span> <span style="color: #000066;">Foreground</span>=<span style="color: #ff0000;">&quot;White&quot;</span> </span>
<span style="color: #009900;">  <span style="color: #000000; font-weight: bold;">&lt;local:BindingUtil.MultiBindings<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;local:MultiBindings<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;local:MultiBinding</span> <span style="color: #000066;">TargetProperty</span>=<span style="color: #ff0000;">&quot;Text&quot;</span></span>
<span style="color: #009900;">                          <span style="color: #000066;">Converter</span>=<span style="color: #ff0000;">&quot;{StaticResource TitleConverter}&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;local:BindingCollection<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
          <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Binding</span> <span style="color: #000066;">Path</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;Binding</span> <span style="color: #000066;">Path</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;/local:BindingCollection<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/local:MultiBinding<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;local:MultiBinding</span> <span style="color: #000066;">TargetProperty</span>=<span style="color: #ff0000;">&quot;ToolTipService.ToolTip&quot;</span></span>
<span style="color: #009900;">                          <span style="color: #000066;">Converter</span>=<span style="color: #ff0000;">&quot;{StaticResource TitleConverter}&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;local:BindingCollection<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
          <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Binding</span> <span style="color: #000066;">Path</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;Binding</span> <span style="color: #000066;">Path</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;/local:BindingCollection<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/local:MultiBinding<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/local:MultiBindings<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/local:BindingUtil.MultiBindings<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/TextBlock<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Here the Text property and attached ToolTip property of the TextBlock are bound to both the Surname and Forename property of the business object which is set as the DataContext of our view.</p>
<p>The value converter 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> TitleConverter <span style="color: #008000;">:</span> IMultiValueConverter
<span style="color: #008000;">&#123;</span>
&nbsp;
  <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><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> values, 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: #6666cc; font-weight: bold;">string</span> forename <span style="color: #008000;">=</span> values<span style="color: #008000;">&#91;</span><span style="color: #FF0000;">0</span><span style="color: #008000;">&#93;</span> <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: #6666cc; font-weight: bold;">string</span> surname <span style="color: #008000;">=</span> values<span style="color: #008000;">&#91;</span><span style="color: #FF0000;">1</span><span style="color: #008000;">&#93;</span> <span style="color: #0600FF; font-weight: bold;">as</span> <span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Format</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;{0}, {1}&quot;</span>, surname, forename<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>In the example below you can see that as you change the forename or surname, the title text and tooltip are updated by the multibinding.</p>
<div> <object width="200" height="150" 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/08/SLMultiBindingOne.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 how does this work?</p>
<p>When a multibinding is created and added to an element via the BindingUtil.MultiBindings attached property, the MultiBinding instance is added to a virtual-branch, this is a branch of the visual tree that obtains the DataContext of the element to which it is bound, but is not added to the visual tree itself. The MultiBinding then creates a BindingSlave instance for each of the given Bindings. These ‘slave’ elements inherit the MultiBinding DataContext and are used to evaluate each of the individual Bindings. The MultiBinding instance aggregate the results of each binding with the IMultiValueConverter used to compute the ConvertedValue property which is bound to the target property on the element to which this MultiBinding as attached.</p>
<p><img src="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2009/06/virtualbranch.png" alt="" title="virtualbranch" width="604" height="394" class="aligncenter size-full wp-image-355" /></p>
<p><strong>ElementName binding</strong></p>
<p>So why does the above solution not work if one of the multibindings uses ElementName to locate the source rather than using the inherited DataContext? The problem here is that the MultiBinding and its BindingSlave instances are located in a virtual branch and are therefore not in the same <a href="http://msdn.microsoft.com/en-us/library/cc189026%28VS.95%29.aspx">namescope</a> as the target element. As a result, they cannot perform look up of named elements.</p>
<p>In order to solve this problem I created a BindingSlave subclass specifically for ElementName binding. This slave locates the source element named via the ElementName property and sets it as the Source of the binding it uses to compute its Value property.</p>
<p>The only minor complication I encountered is that the MultiBinding might be constructed before the element referenced via ElementName. For this reason the binding slave must handle LayoutUpdated events to ensure that the named element is located if it is constructed after the multibinding.</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> ElementNameBindingSlave <span style="color: #008000;">:</span> BindingSlave
<span style="color: #008000;">&#123;</span>
  <span style="color: #0600FF; font-weight: bold;">private</span> FrameworkElement _multiBindingTarget<span style="color: #008000;">;</span>
&nbsp;
  <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
  <span style="color: #008080; font-style: italic;">/// The source element named in the ElementName binding</span>
  <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
  <span style="color: #0600FF; font-weight: bold;">private</span> FrameworkElement _elementNameSource<span style="color: #008000;">;</span>
&nbsp;
  <span style="color: #0600FF; font-weight: bold;">private</span> Binding _binding<span style="color: #008000;">;</span>
&nbsp;
  <span style="color: #0600FF; font-weight: bold;">public</span> ElementNameBindingSlave<span style="color: #008000;">&#40;</span>FrameworkElement target, Binding binding<span style="color: #008000;">&#41;</span>
  <span style="color: #008000;">&#123;</span>
    _multiBindingTarget <span style="color: #008000;">=</span> target<span style="color: #008000;">;</span>
    _binding <span style="color: #008000;">=</span> binding<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">// try to locate the named element</span>
    ResolveElementNameBinding<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    _multiBindingTarget<span style="color: #008000;">.</span><span style="color: #0000FF;">LayoutUpdated</span> <span style="color: #008000;">+=</span> MultiBindingTarget_LayoutUpdated<span style="color: #008000;">;</span>
  <span style="color: #008000;">&#125;</span>
&nbsp;
  <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
  <span style="color: #008080; font-style: italic;">/// Try to locate the named element. If the element can be located, create the required</span>
  <span style="color: #008080; font-style: italic;">/// binding.</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> ResolveElementNameBinding<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
  <span style="color: #008000;">&#123;</span>
    _elementNameSource <span style="color: #008000;">=</span> _multiBindingTarget<span style="color: #008000;">.</span><span style="color: #0000FF;">FindName</span><span style="color: #008000;">&#40;</span>_binding<span style="color: #008000;">.</span><span style="color: #0000FF;">ElementName</span><span style="color: #008000;">&#41;</span> <span style="color: #0600FF; font-weight: bold;">as</span> FrameworkElement<span style="color: #008000;">;</span>
    <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>_elementNameSource <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>
      SetBinding<span style="color: #008000;">&#40;</span>BindingSlave<span style="color: #008000;">.</span><span style="color: #0000FF;">ValueProperty</span>, <span style="color: #008000;">new</span> Binding<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
      <span style="color: #008000;">&#123;</span>
        Source <span style="color: #008000;">=</span> _elementNameSource,
        Path <span style="color: #008000;">=</span> _binding<span style="color: #008000;">.</span><span style="color: #0000FF;">Path</span>,
        Converter <span style="color: #008000;">=</span> _binding<span style="color: #008000;">.</span><span style="color: #0000FF;">Converter</span>,
        ConverterParameter <span style="color: #008000;">=</span> _binding<span style="color: #008000;">.</span><span style="color: #0000FF;">ConverterParameter</span>
      <span style="color: #008000;">&#125;</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;">private</span> <span style="color: #6666cc; font-weight: bold;">void</span> MultiBindingTarget_LayoutUpdated<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: #008080; font-style: italic;">// try to locate the named element </span>
    ResolveElementNameBinding<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>The example below demonstrates element name binding by binding the Value of two Slider elements to a TextBlock which displays the sum of the two values.</p>
<div> <object width="200" height="150" 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/08/SLMultiBindingTwo.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>

<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;TextBlock</span> <span style="color: #000066;">Grid.Column</span>=<span style="color: #ff0000;">&quot;1&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;local:BindingUtil.MultiBindings<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;local:MultiBindings<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;local:MultiBinding</span> <span style="color: #000066;">TargetProperty</span>=<span style="color: #ff0000;">&quot;Text&quot;</span></span>
<span style="color: #009900;">                          <span style="color: #000066;">Converter</span>=<span style="color: #ff0000;">&quot;{StaticResource SliderValueConverter}&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;local:BindingCollection<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
          <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Binding</span> <span style="color: #000066;">ElementName</span>=<span style="color: #ff0000;">&quot;sliderOne&quot;</span> <span style="color: #000066;">Path</span>=<span style="color: #ff0000;">&quot;Value&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
          <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Binding</span> <span style="color: #000066;">ElementName</span>=<span style="color: #ff0000;">&quot;sliderTwo&quot;</span> <span style="color: #000066;">Path</span>=<span style="color: #ff0000;">&quot;Value&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/local:BindingCollection<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/local:MultiBinding<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/local:MultiBindings<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/local:BindingUtil.MultiBindings<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/TextBlock<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Slider</span> <span style="color: #000066;">x:Name</span>=<span style="color: #ff0000;">&quot;sliderOne&quot;</span> <span style="color: #000066;">Value</span>=<span style="color: #ff0000;">&quot;10&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;Slider</span> <span style="color: #000066;">x:Name</span>=<span style="color: #ff0000;">&quot;sliderTwo&quot;</span>  <span style="color: #000066;">Value</span>=<span style="color: #ff0000;">&quot;20&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span></pre></div></div>

<p>Here is the value converter that is used to compute the sum:</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> SliderValueConverter <span style="color: #008000;">:</span> IMultiValueConverter
<span style="color: #008000;">&#123;</span>
&nbsp;
  <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><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> values, Type targetType, <span style="color: #6666cc; font-weight: bold;">object</span> parameter, <span style="color: #000000;">System.<span style="color: #0000FF;">Globalization</span></span><span style="color: #008000;">.</span><span style="color: #0000FF;">CultureInfo</span> culture<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>values<span style="color: #008000;">.</span><span style="color: #0000FF;">Length</span> <span style="color: #008000;">!=</span> <span style="color: #FF0000;">2</span> <span style="color: #008000;">||</span>
        values<span style="color: #008000;">&#91;</span><span style="color: #FF0000;">0</span><span style="color: #008000;">&#93;</span> <span style="color: #008000;">==</span> <span style="color: #0600FF; font-weight: bold;">null</span> <span style="color: #008000;">||</span>
        values<span style="color: #008000;">&#91;</span><span style="color: #FF0000;">1</span><span style="color: #008000;">&#93;</span> <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: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">double</span><span style="color: #008000;">&#41;</span>values<span style="color: #008000;">&#91;</span><span style="color: #FF0000;">0</span><span style="color: #008000;">&#93;</span> <span style="color: #008000;">+</span> <span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">double</span><span style="color: #008000;">&#41;</span>values<span style="color: #008000;">&#91;</span><span style="color: #FF0000;">1</span><span style="color: #008000;">&#93;</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>You could of course use element name binding to combine the surname / forename in the first example in this blog post, but in this context it is more likely that you will want to back your UI with a business object. It is also possible to mix element name and regular (i.e. Source=DataContext) binding.</p>
<p>I find multibindings which use ElementName references most useful when creating complex UI layouts that do not lend themselves to being implemented using Panels. For a good example see my article on <a href="http://www.codeproject.com/KB/WPF/WpfWinFormsBulletGraphs.aspx">the implementation of a BulletGraph control </a>which makes extensive use of this technique in order that the layout of the control is performed entirely within XAML.</p>
<p><strong>TwoWay Binding</strong></p>
<p>A two-way multibinding must be able to handle updates to the combined value and split it up into its constituent parts in order to update the multiple source bindings. In the first example where a forename and surname property are combined into a “surname, forename” string it is possible to convert back the other way, but in the example above where the values of two Sliders are combined a reverse conversion is not possible.</p>
<p>Modifying this multibinding solution to permit two way binding was relatively straightforward. A property changed event handler was added to the MultiBindig.ConverterValue (which is bound to the multi binding target) so that we can determine when changes have been made. This handler then uses the IMultiValueConverter to convert the value into the multiple source properties and updates the binding slaves accordingly:</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;">/// Handles property changes for the ConvertedValue property</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> OnConvertedValuePropertyChanged<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    OnPropertyChanged<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;ConvertedValue&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">// if the value is being updated, but not due to one of the multibindings</span>
    <span style="color: #008080; font-style: italic;">// then the target property has changed.</span>
    <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span><span style="color: #008000;">!</span>_updatingConvertedValue<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
      <span style="color: #008080; font-style: italic;">// convert back</span>
      <span style="color: #6666cc; font-weight: bold;">object</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> convertedValues <span style="color: #008000;">=</span> Converter<span style="color: #008000;">.</span><span style="color: #0000FF;">ConvertBack</span><span style="color: #008000;">&#40;</span>ConvertedValue, <span style="color: #0600FF; font-weight: bold;">null</span>,
          ConverterParameter, CultureInfo<span style="color: #008000;">.</span><span style="color: #0000FF;">InvariantCulture</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
      <span style="color: #008080; font-style: italic;">// update all the binding slaves</span>
      <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>Children<span style="color: #008000;">.</span><span style="color: #0000FF;">Count</span> <span style="color: #008000;">==</span> convertedValues<span style="color: #008000;">.</span><span style="color: #0000FF;">Length</span><span style="color: #008000;">&#41;</span>
      <span style="color: #008000;">&#123;</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> index <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span> index <span style="color: #008000;">&lt;</span> convertedValues<span style="color: #008000;">.</span><span style="color: #0000FF;">Length</span><span style="color: #008000;">;</span> index<span style="color: #008000;">++</span><span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
          <span style="color: #008000;">&#40;</span><span style="color: #008000;">&#40;</span>BindingSlave<span style="color: #008000;">&#41;</span>Children<span style="color: #008000;">&#91;</span>index<span style="color: #008000;">&#93;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Value</span> <span style="color: #008000;">=</span> convertedValues<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>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>In order to use two way multibinding both the multibinding mode <em>and</em> the bindings within the BindingCollection must be set to TwoWay. See the example given below:</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;TextBlock</span> <span style="color: #000066;">Text</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.Column</span>=<span style="color: #ff0000;">&quot;1&quot;</span> <span style="color: #000066;">Text</span>=<span style="color: #ff0000;">&quot;{Binding Path=Surname, Mode=TwoWay}&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;TextBlock</span> <span style="color: #000066;">Grid.Row</span>=<span style="color: #ff0000;">&quot;1&quot;</span> <span style="color: #000066;">Text</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.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 Path=Forename, Mode=TwoWay}&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;TextBlock</span> <span style="color: #000066;">Grid.Row</span>=<span style="color: #ff0000;">&quot;2&quot;</span> <span style="color: #000066;">Text</span>=<span style="color: #ff0000;">&quot;Combined:&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: #000000; font-weight: bold;">&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;local:BindingUtil.MultiBindings<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;local:MultiBindings<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;local:MultiBinding</span> <span style="color: #000066;">TargetProperty</span>=<span style="color: #ff0000;">&quot;Text&quot;</span></span>
<span style="color: #009900;">                        <span style="color: #000066;">Converter</span>=<span style="color: #ff0000;">&quot;{StaticResource TitleConverter}&quot;</span></span>
<span style="color: #009900;">                        <span style="color: #000066;">Mode</span>=<span style="color: #ff0000;">&quot;TwoWay&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;local:BindingCollection<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
          <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Binding</span> <span style="color: #000066;">Path</span>=<span style="color: #ff0000;">&quot;Surname&quot;</span> <span style="color: #000066;">Mode</span>=<span style="color: #ff0000;">&quot;TwoWay&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
          <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Binding</span> <span style="color: #000066;">Path</span>=<span style="color: #ff0000;">&quot;Forename&quot;</span> <span style="color: #000066;">Mode</span>=<span style="color: #ff0000;">&quot;TwoWay&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/local:BindingCollection<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/local:MultiBinding<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/local:MultiBindings<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/local:BindingUtil.MultiBindings<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/TextBox<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>You can have  try of two way multibinding below where the values of the forename and surname text boxes are combined in the box below. However, you ca also make updates to the combined result which will then be converted back into its constituent parts:</p>
<div> <object width="300" height="150" 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/08/SLMultiBindingThree.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>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> TitleConverter <span style="color: #008000;">:</span> IMultiValueConverter
<span style="color: #008000;">&#123;</span>
  <span style="color: #008080;">#region IMultiValueConverter Members</span>
&nbsp;
  <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><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> values, Type targetType,
    <span style="color: #6666cc; font-weight: bold;">object</span> parameter, <span style="color: #000000;">System.<span style="color: #0000FF;">Globalization</span></span><span style="color: #008000;">.</span><span style="color: #0000FF;">CultureInfo</span> culture<span style="color: #008000;">&#41;</span>
  <span style="color: #008000;">&#123;</span>
    <span style="color: #6666cc; font-weight: bold;">string</span> forename <span style="color: #008000;">=</span> values<span style="color: #008000;">&#91;</span><span style="color: #FF0000;">0</span><span style="color: #008000;">&#93;</span> <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: #6666cc; font-weight: bold;">string</span> surname <span style="color: #008000;">=</span> values<span style="color: #008000;">&#91;</span><span style="color: #FF0000;">1</span><span style="color: #008000;">&#93;</span> <span style="color: #0600FF; font-weight: bold;">as</span> <span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Format</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;{0}, {1}&quot;</span>, surname, forename<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: #6666cc; font-weight: bold;">object</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> ConvertBack<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">object</span> value, Type<span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> targetTypes,
    <span style="color: #6666cc; font-weight: bold;">object</span> parameter, <span style="color: #000000;">System.<span style="color: #0000FF;">Globalization</span></span><span style="color: #008000;">.</span><span style="color: #0000FF;">CultureInfo</span> culture<span style="color: #008000;">&#41;</span>
  <span style="color: #008000;">&#123;</span>
    <span style="color: #6666cc; font-weight: bold;">string</span> source <span style="color: #008000;">=</span> value <span style="color: #0600FF; font-weight: bold;">as</span> <span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">;</span>
    var pos <span style="color: #008000;">=</span> source<span style="color: #008000;">.</span><span style="color: #0000FF;">IndexOf</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;, &quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #6666cc; font-weight: bold;">string</span> forename <span style="color: #008000;">=</span> source<span style="color: #008000;">.</span><span style="color: #0000FF;">Substring</span><span style="color: #008000;">&#40;</span>pos <span style="color: #008000;">+</span> <span style="color: #FF0000;">2</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #6666cc; font-weight: bold;">string</span> surname <span style="color: #008000;">=</span> source<span style="color: #008000;">.</span><span style="color: #0000FF;">Substring</span><span style="color: #008000;">&#40;</span><span style="color: #FF0000;">0</span>, pos<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #008000;">new</span> <span style="color: #6666cc; font-weight: bold;">object</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> <span style="color: #008000;">&#123;</span> forename, surname <span style="color: #008000;">&#125;</span><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>So, there you have it, two-way and element name multibinding <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 source, including a WPF build (thanks to <a href="http://www.olsonsoft.com/blogs/stefanolson/">Stefan Olson</a>) here: <a href='http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2010/08/SLMultiBinding.zip'>SLMultiBinding.zip</a> </p>
<p>Now &#8230; go forth and multibind.</p>
<p>Regards, Colin E.</p>

]]></content:encoded>
			<wfw:commentRss>http://www.scottlogic.co.uk/blog/colin/2010/08/silverlight-multibinding-updated-adding-support-for-elementname-and-twoway-binding/feed/</wfw:commentRss>
		<slash:comments>62</slash:comments>
		</item>
		<item>
		<title>Silverlight MultiBinding solution for Silverlight 4</title>
		<link>http://www.scottlogic.co.uk/blog/colin/2010/05/silverlight-multibinding-solution-for-silverlight-4/</link>
		<comments>http://www.scottlogic.co.uk/blog/colin/2010/05/silverlight-multibinding-solution-for-silverlight-4/#comments</comments>
		<pubDate>Mon, 10 May 2010 07:22:17 +0000</pubDate>
		<dc:creator>Colin Eberhardt</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[binding]]></category>
		<category><![CDATA[multibinding]]></category>
		<category><![CDATA[silverlight]]></category>

		<guid isPermaLink="false">http://www.scottlogic.co.uk/blog/colin/?p=650</guid>
		<description><![CDATA[In this post I describe an update to the Silverlight MultiBinding solution I presented last year. This update includes support for Silverlight 4, attached properties and multiple bindings on a single object. UPDATE: I have updated this code to include ElementName and TwoWay binding. Grab the latest copy here. MultiBinding is a WPF feature that [...]]]></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%252F05%252Fsilverlight-multibinding-solution-for-silverlight-4%252F%22%2C%20%22style%22%3A%20%22big%22%2C%20%22title%22%3A%20%22Silverlight%20MultiBinding%20solution%20for%20Silverlight%204%20%23%22%20%7D);"></div>
<p><em>In this post I describe an update to the Silverlight MultiBinding solution I presented last year. This update includes support for Silverlight 4, attached properties and multiple bindings on a single object.</em></p>
<p><b>UPDATE:</b> I have updated this code to include ElementName and TwoWay binding. <a href="http://www.scottlogic.co.uk/blog/colin/2010/08/silverlight-multibinding-updated-adding-support-for-elementname-and-twoway-binding/">Grab the latest copy here</a>.</p>
<p>MultiBinding is a WPF feature that allows you to bind a single property to a number of sources, with the source values being combined by a value converter. This is a feature that is missing from Silverlight. About a year ago I developed a <a href="http://www.scottlogic.co.uk/blog/colin/2009/06/silverlight-multibindings-how-to-attached-mutiple-bindings-to-a-single-property/">MultiBinding solution for Silverlight</a>, which has proven very popular! I even had an email from an Microsoft Attorney asking if they could use it in the <a href="http://www.silverlight.net/content/samples/apps/facebookclient/sfcquickinstall.aspx">Silverlight Facebook client</a> (How cool is that <img src='http://www.scottlogic.co.uk/blog/colin/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' />  ). I was also very happy when <a href="http://http://www.olsonsoft.com/blogs/stefanolson/">Stefan Olson</a> made a few updates to this code to allow multiple MultiBindings on a single object and spotted the SL4 issue. This blog post is a quick demonstration of these new features &#8230;</p>
<p>The following application is an example of MultiBindings in action:</p>
<div id="slPluginHost" > <object id="SilverlightPlugin" width="200" height="150" 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/05/SLMultiBinding.xap"/><a href="http://go.microsoft.com/fwlink/?LinkID=149156"  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>In the above application, the TextBox at the top of the page is bound to both the surname and forename properties of our data-object via converter that takes the first letter of the forename and the surname. If you edit the surname or forename (hitting enter or changing focus to commit), the title is updated automatically. The title tooltip is bound to the all three object properties via a different value converter that  concatenates all three.</p>
<p>The XAML for this binding is show below:</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;TextBlock</span> <span style="color: #000066;">x:Name</span>=<span style="color: #ff0000;">&quot;Block&quot;</span> <span style="color: #000066;">Foreground</span>=<span style="color: #ff0000;">&quot;White&quot;</span> <span style="color: #000066;">FontSize</span>=<span style="color: #ff0000;">&quot;13&quot;</span> <span style="color: #000066;">Margin</span>=<span style="color: #ff0000;">&quot;5,0,0,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;local:BindingUtil.MultiBindings<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;local:MultiBindings<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;local:MultiBinding</span> <span style="color: #000066;">TargetProperty</span>=<span style="color: #ff0000;">&quot;Text&quot;</span></span>
<span style="color: #009900;">                                <span style="color: #000066;">Converter</span>=<span style="color: #ff0000;">&quot;{StaticResource TitleSummaryConverter}&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;local:MultiBinding.Bindings<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;local:BindingCollection<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Binding</span> <span style="color: #000066;">Path</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;Binding</span> <span style="color: #000066;">Path</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;/local:BindingCollection<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/local:MultiBinding.Bindings<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/local:MultiBinding<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;local:MultiBinding</span> <span style="color: #000066;">TargetProperty</span>=<span style="color: #ff0000;">&quot;ToolTipService.ToolTip&quot;</span></span>
<span style="color: #009900;">                                <span style="color: #000066;">Converter</span>=<span style="color: #ff0000;">&quot;{StaticResource TitleConverter}&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;local:MultiBinding.Bindings<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;local:BindingCollection<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Binding</span> <span style="color: #000066;">Path</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;Binding</span> <span style="color: #000066;">Path</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;Binding</span> <span style="color: #000066;">Path</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;/local:BindingCollection<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/local:MultiBinding.Bindings<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/local:MultiBinding<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/local:MultiBindings<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/local:BindingUtil.MultiBindings<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/TextBlock<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>In the above you can see that our TextBlock has two multibindings, one on Forename and Surname, and the other which includes all three properties. Note, the second multibinding is on the ToolTipService.ToolTip attached property.</p>
<p>You can download the source for Silverlight MultiBinding here: <a href='http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2010/05/SLMultiBindingUpdate.zip'>SLMultiBindingUpdate.zip</a> &#8211; thanks again to Stefan Olson who added WPF support to this technique.</p>
<p>If you are interested in the technical details of how this works, I refer you to the <a href="http://www.scottlogic.co.uk/blog/colin/2009/06/silverlight-multibindings-how-to-attached-mutiple-bindings-to-a-single-property/">original article</a> which describes how the code builds a &#8216;virtual&#8217; branch on the visual tree in order to evaluate your bindings:</p>
<p><a href="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2009/06/virtualbranch.png"><img src="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2009/06/virtualbranch.png" alt="" title="virtualbranch" width="604" height="394" class="aligncenter size-full wp-image-355" /></a></p>
<p>I hope this update is of use to SL4 developers. If you have any feedback, please leave a comment below.</p>
<p>You can download the source for Silverlight MultiBinding here: <a href='http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2010/05/SLMultiBindingUpdate.zip'>SLMultiBindingUpdate.zip</a></p>
<p>Regards, Colin E.</p>

]]></content:encoded>
			<wfw:commentRss>http://www.scottlogic.co.uk/blog/colin/2010/05/silverlight-multibinding-solution-for-silverlight-4/feed/</wfw:commentRss>
		<slash:comments>39</slash:comments>
		</item>
		<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>The mini-ViewModel pattern</title>
		<link>http://www.scottlogic.co.uk/blog/colin/2009/08/the-mini-viewmodel-pattern/</link>
		<comments>http://www.scottlogic.co.uk/blog/colin/2009/08/the-mini-viewmodel-pattern/#comments</comments>
		<pubDate>Fri, 07 Aug 2009 16:23:18 +0000</pubDate>
		<dc:creator>Colin Eberhardt</dc:creator>
				<category><![CDATA[codeproject]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[binding]]></category>
		<category><![CDATA[mvvm]]></category>
		<category><![CDATA[silverlight]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://www.scottlogic.co.uk/blog/colin/?p=460</guid>
		<description><![CDATA[The construction of a ViewModel is often seen as the standard technique for solving binding problems within WPF and Silverlight. However, the addition of a ViewModel adds complexity to your code. This post describes an alternative method where a mini-ViewModel is applied directly to the problem areas in the view, leaving the rest to use [...]]]></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%252F08%252Fthe-mini-viewmodel-pattern%252F%22%2C%20%22style%22%3A%20%22big%22%2C%20%22title%22%3A%20%22The%20mini-ViewModel%20pattern%20%23%22%20%7D);"></div>
<p><em>The construction of a ViewModel is often seen as the standard technique for solving binding problems within WPF and Silverlight. However, the addition of a ViewModel adds complexity to your code. This post describes an alternative method where a mini-ViewModel is applied directly to the problem areas in the view, leaving the rest to use simpler, straightforward binding to business objects. </em></p>
<p>One of the features of WPF / Silverlight that appealed to me immediately when I started to learn it was the flexibility of the binding framework. The concepts of DataContext inheritence and flexibility of the value converters results in a lot less glue-code, which makes me a happy developer! However, it does not take long before you start finding examples that just dont fit with the framework and things start to get just little more complex. This blog post describes one such example.</p>
<p>The example used in this blog post is of a very simple application which displays a business card. The business object rendered by the application, <code>ContactDetails</code>, has a number of simple CLR properties. Constructing a UI for viewing this business object is very easy, simply create an instance of this object (in a real application this object might come from a database or web service) and set it as the DataContext of the view:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> Page<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    InitializeComponent<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    ContactDetails details <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> ContactDetails<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        Company <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;Scott Logic Ltd.&quot;</span>,
        Email <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;ceberhardt@scottlogic.co.uk&quot;</span>,
        URL <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;http://www.scottlogic.co.uk&quot;</span>,
        Country <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;UK&quot;</span>,
        FullName <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;Colin Eberhardt&quot;</span>,
        PhoneNumber <span style="color: #008000;">=</span> <span style="color: #FF0000;">4408452241930</span>
    <span style="color: #008000;">&#125;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">DataContext</span> <span style="color: #008000;">=</span> details<span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>We then create some simple XAML with UI elements that bind to the various propeties of our object &#8230;</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;Grid</span> <span style="color: #000066;">x:Name</span>=<span style="color: #ff0000;">&quot;LayoutRoot&quot;</span> <span style="color: #000066;">Background</span>=<span style="color: #ff0000;">&quot;White&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;">BorderBrush</span>=<span style="color: #ff0000;">&quot;LightGray&quot;</span> <span style="color: #000066;">Background</span>=<span style="color: #ff0000;">&quot;White&quot;</span>  <span style="color: #000066;">BorderThickness</span>=<span style="color: #ff0000;">&quot;1.5&quot;</span> <span style="color: #000066;">CornerRadius</span>=<span style="color: #ff0000;">&quot;20&quot;</span></span>
<span style="color: #009900;">        <span style="color: #000066;">VerticalAlignment</span>=<span style="color: #ff0000;">&quot;Center&quot;</span> <span style="color: #000066;">HorizontalAlignment</span>=<span style="color: #ff0000;">&quot;Center&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;">Margin</span>=<span style="color: #ff0000;">&quot;5&quot;</span> <span style="color: #000066;">BorderBrush</span>=<span style="color: #ff0000;">&quot;LightGray&quot;</span> <span style="color: #000066;">BorderThickness</span>=<span style="color: #ff0000;">&quot;1.5&quot;</span> <span style="color: #000066;">CornerRadius</span>=<span style="color: #ff0000;">&quot;15&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.Background<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ImageBrush<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ImageBrush.ImageSource<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;BitmapImage</span> <span style="color: #000066;">UriSource</span>=<span style="color: #ff0000;">&quot;back.jpg&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
                    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/ImageBrush.ImageSource<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/ImageBrush<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/Border.Background<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;StackPanel</span> <span style="color: #000066;">Orientation</span>=<span style="color: #ff0000;">&quot;Vertical&quot;</span> <span style="color: #000066;">Margin</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;TextBlock</span> <span style="color: #000066;">Text</span>=<span style="color: #ff0000;">&quot;{Binding FullName}&quot;</span></span>
<span style="color: #009900;">                           <span style="color: #000066;">FontSize</span>=<span style="color: #ff0000;">&quot;15&quot;</span></span>
<span style="color: #009900;">                           <span style="color: #000066;">FontWeight</span>=<span style="color: #ff0000;">&quot;Bold&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Rectangle</span> <span style="color: #000066;">Stroke</span>=<span style="color: #ff0000;">&quot;DarkGray&quot;</span> <span style="color: #000066;">HorizontalAlignment</span>=<span style="color: #ff0000;">&quot;Stretch&quot;</span></span>
<span style="color: #009900;">                           <span style="color: #000066;">StrokeThickness</span>=<span style="color: #ff0000;">&quot;0.5&quot;</span> <span style="color: #000066;">Height</span>=<span style="color: #ff0000;">&quot;1&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;TextBlock</span> <span style="color: #000066;">Text</span>=<span style="color: #ff0000;">&quot;{Binding Company}&quot;</span> <span style="color: #000066;">Margin</span>=<span style="color: #ff0000;">&quot;0,10,0,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;StackPanel</span> <span style="color: #000066;">Orientation</span>=<span style="color: #ff0000;">&quot;Horizontal&quot;</span> <span style="color: #000000; font-weight: bold;">&gt;</span></span>
                    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;TextBlock</span> <span style="color: #000066;">Text</span>=<span style="color: #ff0000;">&quot;e: &quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
                    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;TextBlock</span> <span style="color: #000066;">Text</span>=<span style="color: #ff0000;">&quot;{Binding Email}&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/StackPanel<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;StackPanel</span> <span style="color: #000066;">Orientation</span>=<span style="color: #ff0000;">&quot;Horizontal&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
                    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;TextBlock</span> <span style="color: #000066;">Text</span>=<span style="color: #ff0000;">&quot;w: &quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
                    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;HyperlinkButton</span> <span style="color: #000066;">Content</span>=<span style="color: #ff0000;">&quot;{Binding URL}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/StackPanel<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;StackPanel</span> <span style="color: #000066;">Orientation</span>=<span style="color: #ff0000;">&quot;Horizontal&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
                    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;TextBlock</span> <span style="color: #000066;">Text</span>=<span style="color: #ff0000;">&quot;p: &quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
                    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;TextBlock</span> <span style="color: #000066;">Text</span>=<span style="color: #ff0000;">&quot;{Binding PhoneNumber}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/StackPanel<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/StackPanel<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>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/Border<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></pre></div></div>

<p>And we get a lovely looking business card:</p>
<p><img src="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2009/07/card.png" alt="card" title="card" width="196" height="129" class="aligncenter size-full wp-image-462" /></p>
<p>One problem with the above example is the phone number, outputting the raw number &#8217;4408452241930&#8242; is not terribly readable, besides phone numbers have a standard format, in this case, the phone number would be represented as &#8216;+44 (0)845 2241930&#8242;. Also, let&#8217;s make the problem more interesting; you might want to highlight the international dialing code in a different colour, or, if the application is being used by a UK client, display the number in a local format without the international code &#8217;0845 2241930&#8242;. So just how do we achieve this?</p>
<p>In order to break the number up into different blocks of text, with different colours (i.e. styles), we need to modify our view to have multiple TextBlocks mapped to the PhoneNumber property of our business object. The part of our view which renders the phone number is modified 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;StackPanel</span> <span style="color: #000066;">Orientation</span>=<span style="color: #ff0000;">&quot;Horizontal&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;TextBlock</span> <span style="color: #000066;">Text</span>=<span style="color: #ff0000;">&quot;p: &quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;TextBlock</span> <span style="color: #000066;">Text</span>=<span style="color: #ff0000;">&quot;... country code ...&quot;</span> <span style="color: #000066;">Foreground</span>=<span style="color: #ff0000;">&quot;LightGray&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;TextBlock</span> <span style="color: #000066;">Text</span>=<span style="color: #ff0000;">&quot;... area code ...&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;TextBlock</span> <span style="color: #000066;">Text</span>=<span style="color: #ff0000;">&quot;... local number ...&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/StackPanel<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>But just how exactly do we bind the properties of these business objects?</p>
<p>One approach would be to use a value converter for each binding in order to extract the required part of the number, for example a CountryCodeValueConverter could be implemented which grabs the first 2 digits of the number. However, this approach is a little inelligent in that it fragments our logic into a number of separate classes, furthermore, if we want country specific formatting this requires the use of multibindings, which can be rather cumbersome if over-used (for a Silverlight implementation of multi bindings see <a href="http://www.scottlogic.co.uk/blog/colin/2009/06/silverlight-multibindings-how-to-attached-mutiple-bindings-to-a-single-property/">my blog post</a> from earlier this year). </p>
<p>Another approach which is often used to tackle tricky binding problems is the use of the Model-View-ViewModel (MVVM) pattern. With this pattern, our ContactDetails object is the Model, we construct a ViewModel which is a UI-oriented abstraction of the Model and it is this which we bind to the View. WPF guru Josh Smith describes MVVM as <a href="http://joshsmithonwpf.wordpress.com/2008/12/01/the-philosophies-of-mvvm/">&#8220;a value converter on steroids&#8221;</a> in order to highlight the usefulness of the pattern in this context.</p>
<p>The basic approach used here is to bind your View to a ViewModel rather than binding it to the business object directly. The ViewModel is specific to the view and wraps the business object (i.e. Model), forwarding the property values and change notification to the View. This extra layer allows us to supplement the properties of the Model object, adding new computed properties which are specific to the View. In this case, these computed properties can be used to expose &#8216;country code&#8217;, &#8216;area code&#8217;, etc&#8230; to our View. </p>
<p><em>(This is a common pattern so I am not going to reproduce the code required here, however, if you are interested, the attached sourcecode accompanying this article contains a regular ViewModel version as well as a mini-ViewModel implementation)</em></p>
<p>Whilst this approach works, my issue with it is that it adds quite a bit of boiler-plate code for wrapping properties, forwarding events etc &#8230; The removal of this glue-code is the exact reason that I like WPF/Silverlight so much! The MVVM pattern is primarily for supporting the designer-developer paradigm and enabling unit testing of UI applications, in my opinion the use of MVVM for anything else is just plain wrong!</p>
<p>So, how can we solve the problem of providing a nicely formatted phone number without the pain of bashing out line-after-line line of boiler-plate MVVM code? My solution to the problem isn&#8217;t to dispose of the MVVM pattern altogether, rather, it is to localise its usage to just the problem area. The first step is to encapsulate the rendering of the phone number as a user control:</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;StackPanel</span> <span style="color: #000066;">Orientation</span>=<span style="color: #ff0000;">&quot;Horizontal&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;TextBlock</span> <span style="color: #000066;">Text</span>=<span style="color: #ff0000;">&quot;p: &quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;local:PhoneNumberControl</span> <span style="color: #000066;">Number</span>=<span style="color: #ff0000;">&quot;{Binding PhoneNumber}&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/StackPanel<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
...</pre></div></div>

<p>&#8230; which probably makes sense anyway from a perspective of good design and code re-use!</p>
<p>Now that we have moved the phone number property within the <code>PhoneNumberControl</code> we have isolated the problem and can deal with it locally. We can create a <code>PhoneNumberControlViewModel</code> which splits the phone number up into its various components and bind this to the <code>PhoneNumberControl</code>.</p>
<p>The control&#8217;s ViewModel looks something like this:</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> PhoneNumberControlViewModel <span style="color: #008000;">:</span> INotifyPropertyChanged
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> PhoneNumberControlViewModel<span style="color: #008000;">&#40;</span>PhoneNumberControl ctrl<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        _ctrl <span style="color: #008000;">=</span> ctrl<span style="color: #008000;">;</span>
        ComputeProperties<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;">// listen to property changes in the control (we are interested</span>
        <span style="color: #008080; font-style: italic;">// in just the Number property)</span>
        _ctrl<span style="color: #008000;">.</span><span style="color: #0000FF;">PropertyChanged</span> <span style="color: #008000;">+=</span> Control_PropertyChanged<span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">private</span> PhoneNumberControl _ctrl<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">string</span> _countryCodeText<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">string</span> _areaCodeText<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">string</span> _localNumberText<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">string</span> CountryCodeText
    <span style="color: #008000;">&#123;</span>
        get <span style="color: #008000;">&#123;</span> <span style="color: #0600FF; font-weight: bold;">return</span> _countryCodeText<span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
        set <span style="color: #008000;">&#123;</span> _countryCodeText <span style="color: #008000;">=</span> value<span style="color: #008000;">;</span> OnPropertyChanged<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;CountryCodeText&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;">string</span> AreaCodeText
    <span style="color: #008000;">&#123;</span>
        get <span style="color: #008000;">&#123;</span> <span style="color: #0600FF; font-weight: bold;">return</span> _areaCodeText<span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
        set <span style="color: #008000;">&#123;</span> _areaCodeText <span style="color: #008000;">=</span> value<span style="color: #008000;">;</span> OnPropertyChanged<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;AreaCodeText&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;">string</span> LocalNumberText
    <span style="color: #008000;">&#123;</span>
        get <span style="color: #008000;">&#123;</span> <span style="color: #0600FF; font-weight: bold;">return</span> _localNumberText<span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
        set <span style="color: #008000;">&#123;</span> _localNumberText <span style="color: #008000;">=</span> value<span style="color: #008000;">;</span> OnPropertyChanged<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;LocalNumberText&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;">private</span> <span style="color: #6666cc; font-weight: bold;">void</span> Control_PropertyChanged<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">object</span> sender, PropertyChangedEventArgs 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>e<span style="color: #008000;">.</span><span style="color: #0000FF;">PropertyName</span> <span style="color: #008000;">==</span> <span style="color: #666666;">&quot;Number&quot;</span> <span style="color: #008000;">||</span> e<span style="color: #008000;">.</span><span style="color: #0000FF;">PropertyName</span> <span style="color: #008000;">==</span> <span style="color: #666666;">&quot;Country&quot;</span><span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            ComputeProperties<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>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">void</span> ComputeProperties<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #6666cc; font-weight: bold;">string</span> formattedNumber <span style="color: #008000;">=</span> _ctrl<span style="color: #008000;">.</span><span style="color: #0000FF;">Number</span><span style="color: #008000;">.</span><span style="color: #0000FF;">ToString</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>           
        CountryCodeText <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;+&quot;</span> <span style="color: #008000;">+</span> formattedNumber<span style="color: #008000;">.</span><span style="color: #0000FF;">Substring</span><span style="color: #008000;">&#40;</span><span style="color: #FF0000;">0</span>, <span style="color: #FF0000;">2</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        AreaCodeText <span style="color: #008000;">=</span> <span style="color: #666666;">&quot; (&quot;</span> <span style="color: #008000;">+</span> formattedNumber<span style="color: #008000;">.</span><span style="color: #0000FF;">Substring</span><span style="color: #008000;">&#40;</span><span style="color: #FF0000;">2</span>, <span style="color: #FF0000;">1</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">+</span> <span style="color: #666666;">&quot;)&quot;</span> <span style="color: #008000;">+</span> formattedNumber<span style="color: #008000;">.</span><span style="color: #0000FF;">Substring</span><span style="color: #008000;">&#40;</span><span style="color: #FF0000;">3</span>, <span style="color: #FF0000;">3</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        LocalNumberText <span style="color: #008000;">=</span> <span style="color: #666666;">&quot; &quot;</span> <span style="color: #008000;">+</span> formattedNumber<span style="color: #008000;">.</span><span style="color: #0000FF;">Substring</span><span style="color: #008000;">&#40;</span><span style="color: #FF0000;">6</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>Note that here the ViewModel is &#8216;wrapping&#8217; the <code>PhoneNumberControl</code> rather than an instance of some Business / Model object.</p>
<p>Now we just set our ViewModel as the DataContext for the View, as per the typical usage of this pattern:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> PhoneNumberControl<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    InitializeComponent<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;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">DataContext</span> <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> PhoneNumberControlViewModel<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></pre></div></div>

<p>&#8230; and it doesn&#8217;t work. If you try the above, you will find that the binding on the <code>PhoneNumberControl</code>s Number property no longer works. So why is this? if you look back at where the <code>PhoneNumberControl</code> instance is defined in our business card&#8217;s XAML markup you see that its Number property is bound 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;local:PhoneNumberControl</span> <span style="color: #000066;">Number</span>=<span style="color: #ff0000;">&quot;{Binding PhoneNumber}&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span></pre></div></div>

<p>The source of this binding is not explicitly set, so will default to using the DataContext of the <code>PhoneNumberControl</code> instance. However, we have just changed this DataContext in our constructor to something else &#8230; oops!</p>
<p>Solving this problem is actually quite simple, the <code>PhoneNumberControl</code> markup is 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;UserControl</span> <span style="color: #000066;">x:Class</span>=<span style="color: #ff0000;">&quot;SLMiniViewModel.PhoneNumberControl&quot;</span></span>
<span style="color: #009900;">    <span style="color: #000066;">xmlns</span>=<span style="color: #ff0000;">&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;</span> </span>
<span style="color: #009900;">    <span style="color: #000066;">xmlns:x</span>=<span style="color: #ff0000;">&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;StackPanel</span> <span style="color: #000066;">x:Name</span>=<span style="color: #ff0000;">&quot;LayoutRoot&quot;</span> <span style="color: #000066;">Orientation</span>=<span style="color: #ff0000;">&quot;Horizontal&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;TextBlock</span> <span style="color: #000066;">Text</span>=<span style="color: #ff0000;">&quot;{Binding CountryCodeText}&quot;</span> <span style="color: #000066;">Foreground</span>=<span style="color: #ff0000;">&quot;DarkGray&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;TextBlock</span> <span style="color: #000066;">Text</span>=<span style="color: #ff0000;">&quot;{Binding AreaCodeText}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;TextBlock</span> <span style="color: #000066;">Text</span>=<span style="color: #ff0000;">&quot;{Binding LocalNumberText}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/StackPanel<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/UserControl<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>If we modify our binding to the ViewModel 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> PhoneNumberControl<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    InitializeComponent<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    LayoutRoot<span style="color: #008000;">.</span><span style="color: #0000FF;">DataContext</span> <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> PhoneNumberControlViewModel<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></pre></div></div>

<p>The subtle difference being that the ViewModel is now bound to the StackPanel which is the root of our visual tree within the control. This means that the <code>PhoneNumberControl</code> DataContext is still inherited from the business card and is our business object instance, the DataContext switch to the ViewModel is now neatly tucked just within the <code>PhoneNumberControl</code>s visual tree, and it is this DataContext which our TextBlocks will inherit and bind to.</p>
<p>The result is that we can now use our mini-ViewModel embedded within the <code>PhoneNumberControl</code> to expose properties which are more amenable to binding to our View:</p>
<p><img src="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2009/08/card2.png" alt="card2" title="card2" width="210" height="143" class="aligncenter size-full wp-image-485" /></p>
<p>Whilst this is a quite trivial example, in real-world applications, more complex examples where the data representation within the View is dependant on a number of properties are quite common. The source code accompanying this article extends the example a little further by making the formatting dependant on a second property of the business object. This is the sort of problem that would either push you towards multi-binding and numerous fragmented value converters, or a ViewModel.</p>
<p><strong>In conclusion</strong>, the use of a mini-ViewModel which is embedded within a <code>UserControl</code> allows you to solve tricky binding problems without being weighed down by rolling out the MVVM pattern across your entire View. I am not against the MVVM pattern in itself, however I do firmly believe that it should only be used to solve the problems which it is was specifically designed for, i.e. supporting the designer-developer workflow and unit testing.</p>
<p>You can download the source-code for this article: <a href='http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2009/08/SLMiniViewModel.zip'>SLMiniViewModel.zip</a> &#8211; this project contains both MVVM and mini-MVVM implementations (count the number of lines in the ViewModel and contrast it with the mini-ViewModel).</p>
<p>Regards, Colin E.</p>

]]></content:encoded>
			<wfw:commentRss>http://www.scottlogic.co.uk/blog/colin/2009/08/the-mini-viewmodel-pattern/feed/</wfw:commentRss>
		<slash:comments>21</slash:comments>
		</item>
		<item>
		<title>Silverlight MultiBindings, How to attached multiple bindings to a single property.</title>
		<link>http://www.scottlogic.co.uk/blog/colin/2009/06/silverlight-multibindings-how-to-attached-mutiple-bindings-to-a-single-property/</link>
		<comments>http://www.scottlogic.co.uk/blog/colin/2009/06/silverlight-multibindings-how-to-attached-mutiple-bindings-to-a-single-property/#comments</comments>
		<pubDate>Thu, 25 Jun 2009 10:53:56 +0000</pubDate>
		<dc:creator>Colin Eberhardt</dc:creator>
				<category><![CDATA[codeproject]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[binding]]></category>
		<category><![CDATA[multibinding]]></category>
		<category><![CDATA[silverlight]]></category>

		<guid isPermaLink="false">http://www.scottlogic.co.uk/blog/colin/?p=347</guid>
		<description><![CDATA[This blog posts describes a technique for associating multiple bindings with a single dependency property within Silverlight applications. WPF already has this functionality in the form of MultiBindings, the code in this post emulates this function. UPDATE: Silverlight 4, attached properties and multiple property bindings are all supported in my latest update here. The simple [...]]]></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%252F06%252Fsilverlight-multibindings-how-to-attached-mutiple-bindings-to-a-single-property%252F%22%2C%20%22style%22%3A%20%22big%22%2C%20%22title%22%3A%20%22Silverlight%20MultiBindings%2C%20How%20to%20attached%20multiple%20bindings%20to%20a%20single%20property.%20%23%22%20%7D);"></div>
<p><em>This blog posts describes a technique for associating multiple bindings with a single dependency property within Silverlight applications. WPF already has this functionality in the form of MultiBindings, the code in this post emulates this function.</em></p>
<p><b>UPDATE:</b> Silverlight 4, attached properties and multiple property bindings are all supported in my <a href="http://www.scottlogic.co.uk/blog/colin/2010/05/silverlight-multibinding-solution-for-silverlight-4/">latest update here</a>.</p>
<p>The simple application below demonstrates this technique, where there are three data-entry text boxes bound to the individual properties of a simple Person object, with the title text block being bound to <strong>both</strong> the Forename and Surname properties. Try editing the surname or forename fields and watch as the title is updated.</p>
<div id="slPluginHost" > <object id="SilverlightPlugin" width="200" height="150" 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/06/SLMultiBinding.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 XAML for this application looks something like this (superfluous properties/ elements removed for clarity):</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;TextBlock</span> <span style="color: #000066;">Foreground</span>=<span style="color: #ff0000;">&quot;White&quot;</span> <span style="color: #000066;">FontSize</span>=<span style="color: #ff0000;">&quot;13&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;local:BindingUtil.MultiBinding<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;local:MultiBinding</span> <span style="color: #000066;">TargetProperty</span>=<span style="color: #ff0000;">&quot;Text&quot;</span> <span style="color: #000066;">Converter</span>=<span style="color: #ff0000;">&quot;{StaticResource TitleConverter}&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Binding</span> <span style="color: #000066;">Path</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;Binding</span> <span style="color: #000066;">Path</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;/local:MultiBinding<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/local:BindingUtil.MultiBinding<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/TextBlock<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;TextBlock</span> <span style="color: #000066;">Text</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;">Text</span>=<span style="color: #ff0000;">&quot;{Binding Path=Surname, Mode=TwoWay}&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;TextBlock</span> <span style="color: #000066;">Text</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;">Text</span>=<span style="color: #ff0000;">&quot;{Binding Path=Forename, Mode=TwoWay}&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;TextBlock</span> <span style="color: #000066;">Text</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;">Text</span>=<span style="color: #ff0000;">&quot;{Binding Path=Age, Mode=TwoWay}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span></pre></div></div>

<p><strong>The Solution</strong></p>
<p>My solution to the problem of multi-binding was to introduce a class, MultiBinding which is associated with the element which has out multi-binding target property via the BindingUtil.MultiBinding attached property. The following diagram details my idea:</p>
<p><a href="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2009/06/multibinding.png"><img src="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2009/06/multibinding.png" alt="multibinding" title="multibinding" width="402" height="207" class="aligncenter size-full wp-image-353" /></a></p>
<p>The Forename and Surname bindings are bound to properties of the MultiBinding (Exactly which properties we will get onto in a minute). The MultiBinding has an associated Converter of type <a href="http://msdn.microsoft.com/en-us/library/system.windows.data.imultivalueconverter.aspx">IMultiValueConverter</a>, this client supplied class implements the conversion process, 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> TitleConverter <span style="color: #008000;">:</span> IMultiValueConverter
<span style="color: #008000;">&#123;</span>
&nbsp;
  <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><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> values, Type targetType,
    <span style="color: #6666cc; font-weight: bold;">object</span> parameter, <span style="color: #000000;">System.<span style="color: #0000FF;">Globalization</span></span><span style="color: #008000;">.</span><span style="color: #0000FF;">CultureInfo</span> culture<span style="color: #008000;">&#41;</span>
  <span style="color: #008000;">&#123;</span>
    <span style="color: #6666cc; font-weight: bold;">string</span> forename <span style="color: #008000;">=</span> values<span style="color: #008000;">&#91;</span><span style="color: #FF0000;">0</span><span style="color: #008000;">&#93;</span> <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: #6666cc; font-weight: bold;">string</span> surname <span style="color: #008000;">=</span> values<span style="color: #008000;">&#91;</span><span style="color: #FF0000;">1</span><span style="color: #008000;">&#93;</span> <span style="color: #0600FF; font-weight: bold;">as</span> <span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Format</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;{0}, {1}&quot;</span>, surname, forename<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>The IMultiValueConverter interface is much the same as the IValueConverter, except in this case an array of objects are passed to the converter, with each object containing the current bound value for each of our bindings in order.</p>
<p>With this value converter, the MultiBinding class can detect changes in the two bindings, then, recompute the ConvertedValue which is bound to the target property of our TextBlock. This was my initial idea, and it certainly sound quite simple, however it was not quite as easy as it seams on first inspection! </p>
<p><strong>Hijacking the DataContext</strong></p>
<p>Typically when defining a binding we omit the Source property, e.g. {Binding Path=Forename}. When the Binding which this expression represents is associated with an element, the binding source will be the (possibly inherited) DataContext of the target element. Therefore, in order to allow binding on the MultiBinding class, it must be a FrameworkElement, this gives us the DataContext property and the SetBinding() method.</p>
<p>However, there is a problem; each element’s DataContext is inherited from its parent within the visual tree. Our MultiBinding is not within the visual tree and we do not want it to be, therefore it will not participate in DataContext inheritance. What we need to do is ensure that when DataContext changes on the element which the MultiBinding is associated with it, that we ‘push’ this DataContext onto the MultiBinding. With WPF this is easy, FrameWorkElement exposes a DataContextChanged event, (for DPs that do not expose events there’s always the <a href="http://weblogs.asp.net/okloeten/archive/2007/09/18/3940922.aspx">DependencyPropertyDescriptor</a>). However, with Silverlight, neither of these options are available. </p>
<p>My solution here is to create a new attached property and attach it to the target element (our TextBlock in this case), which piggy-backs the DataContext. The code below is from the BindingUtil class, when the MultiBinding class is associated with the target element as an attached property, we also bind its attached DataContextPiggyBack property. We define a static method which is invoked whenever the DatatContext of the target element changes, and here we ‘push’ this new DataContext to the MultiBinding class.</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;">/// Invoked when the MultiBinding property is set on a framework element</span>
<span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</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> OnMultiBindingChanged<span style="color: #008000;">&#40;</span>DependencyObject depObj,
  DependencyPropertyChangedEventArgs e<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
  FrameworkElement targetElement <span style="color: #008000;">=</span> depObj <span style="color: #0600FF; font-weight: bold;">as</span> FrameworkElement<span style="color: #008000;">;</span>
&nbsp;
  <span style="color: #008080; font-style: italic;">// bind the target elements DataContext, to our DataContextPiggyBack property</span>
  <span style="color: #008080; font-style: italic;">// this allows us to get property changed events when the targetElement</span>
  <span style="color: #008080; font-style: italic;">// DataContext changes</span>
  targetElement<span style="color: #008000;">.</span><span style="color: #0000FF;">SetBinding</span><span style="color: #008000;">&#40;</span>BindingUtil<span style="color: #008000;">.</span><span style="color: #0000FF;">DataContextPiggyBackProperty</span>, <span style="color: #008000;">new</span> Binding<span style="color: #008000;">&#40;</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;
&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 DataContextPiggyBackProperty <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;DataContextPiggyBack&quot;</span>,
        <span style="color: #008000;">typeof</span><span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">object</span><span style="color: #008000;">&#41;</span>, <span style="color: #008000;">typeof</span><span style="color: #008000;">&#40;</span>BindingUtil<span style="color: #008000;">&#41;</span>, <span style="color: #008000;">new</span> PropertyMetadata<span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">null</span>,
              <span style="color: #008000;">new</span> PropertyChangedCallback<span style="color: #008000;">&#40;</span>OnDataContextPiggyBackChanged<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</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: #0600FF; font-weight: bold;">static</span> <span style="color: #6666cc; font-weight: bold;">object</span> GetDataContextPiggyBack<span style="color: #008000;">&#40;</span>DependencyObject d<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><span style="color: #6666cc; font-weight: bold;">object</span><span style="color: #008000;">&#41;</span>d<span style="color: #008000;">.</span><span style="color: #0000FF;">GetValue</span><span style="color: #008000;">&#40;</span>DataContextPiggyBackProperty<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> SetDataContextPiggyBack<span style="color: #008000;">&#40;</span>DependencyObject d, <span style="color: #6666cc; font-weight: bold;">object</span> value<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
  d<span style="color: #008000;">.</span><span style="color: #0000FF;">SetValue</span><span style="color: #008000;">&#40;</span>DataContextPiggyBackProperty, value<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;">/// &lt;summary&gt;</span>
<span style="color: #008080; font-style: italic;">/// Handles changes to the DataContextPiggyBack property.</span>
<span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</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> OnDataContextPiggyBackChanged<span style="color: #008000;">&#40;</span>DependencyObject d,
                                                              DependencyPropertyChangedEventArgs e<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
  FrameworkElement targetElement <span style="color: #008000;">=</span> d <span style="color: #0600FF; font-weight: bold;">as</span> FrameworkElement<span style="color: #008000;">;</span>
&nbsp;
  <span style="color: #008080; font-style: italic;">// whenever the targeElement DataContext is changed, copy the updated property</span>
  <span style="color: #008080; font-style: italic;">// value to our MultiBinding.</span>
  MultiBinding relay <span style="color: #008000;">=</span> GetMultiBinding<span style="color: #008000;">&#40;</span>targetElement<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
  relay<span style="color: #008000;">.</span><span style="color: #0000FF;">DataContext</span> <span style="color: #008000;">=</span> targetElement<span style="color: #008000;">.</span><span style="color: #0000FF;">DataContext</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p><strong>Creating targets for the bindings</strong></p>
<p>The MultiBinding class needs to have a property which is a collection of type Binding:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008000;">&#91;</span>ContentProperty<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Bindings&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#93;</span>
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> MultiBinding <span style="color: #008000;">:</span> Panel, INotifyPropertyChanged
<span style="color: #008000;">&#123;</span>
&nbsp;
  <span style="color: #008000;">...</span>
&nbsp;
  <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
  <span style="color: #008080; font-style: italic;">/// The bindings, the result of which are supplied to the converter.</span>
  <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
  <span style="color: #0600FF; font-weight: bold;">public</span> ObservableCollection<span style="color: #008000;">&lt;</span>Binding<span style="color: #008000;">&gt;</span> Bindings <span style="color: #008000;">&#123;</span> get<span style="color: #008000;">;</span> set<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>(Note the use of the ContentProperty attribute, which means that we do not have to explicitly detail Binding collection in XAML using the property element syntax). The problem is, in order for these bindings to be evaluated, they need to be bound to a target property. We could add a number of ‘dummy’ properties to MultiBinding, PropertyOne, PropertyTwo, etc … and bind to these, however this approach is cumbersome and limited. </p>
<p>The solution here is to make MultiBinding a Panel, this allows it to have child elements, each of which will inherit its DataContext. When the MultiBinding class is initialised at the point it is attached, the Initialise method is invoked. This method creates an instance of BindingSlave, a simple FrameworkElement subclass with a single Value property which raises PropertyChanged events when this property changes, for each binding:</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;">/// Creates a BindingSlave for each Binding and binds the Value</span>
<span style="color: #008080; font-style: italic;">/// accordingly.</span>
<span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
<span style="color: #0600FF; font-weight: bold;">internal</span> <span style="color: #6666cc; font-weight: bold;">void</span> Initialise<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;">foreach</span> <span style="color: #008000;">&#40;</span>Binding binding <span style="color: #0600FF; font-weight: bold;">in</span> Bindings<span style="color: #008000;">&#41;</span>
  <span style="color: #008000;">&#123;</span>
    BindingSlave slave <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> BindingSlave<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    slave<span style="color: #008000;">.</span><span style="color: #0000FF;">SetBinding</span><span style="color: #008000;">&#40;</span>BindingSlave<span style="color: #008000;">.</span><span style="color: #0000FF;">ValueProperty</span>, binding<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    slave<span style="color: #008000;">.</span><span style="color: #0000FF;">PropertyChanged</span> <span style="color: #008000;">+=</span> <span style="color: #008000;">new</span> PropertyChangedEventHandler<span style="color: #008000;">&#40;</span>Slave_PropertyChanged<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    Children<span style="color: #008000;">.</span><span style="color: #0000FF;">Add</span><span style="color: #008000;">&#40;</span>slave<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>Whenever a slave property changes, the MultiBinding event handler obtains the current bound values and uses them to re-evaluate the converter:</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;">/// Invoked when any of the BindingSlave's Value property changes.</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> Slave_PropertyChanged<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">object</span> sender, PropertyChangedEventArgs e<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
  List<span style="color: #008000;">&lt;</span><span style="color: #6666cc; font-weight: bold;">object</span><span style="color: #008000;">&gt;</span> values <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> List<span style="color: #008000;">&lt;</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;">foreach</span> <span style="color: #008000;">&#40;</span>BindingSlave slave <span style="color: #0600FF; font-weight: bold;">in</span> Children<span style="color: #008000;">&#41;</span>
  <span style="color: #008000;">&#123;</span>
    values<span style="color: #008000;">.</span><span style="color: #0000FF;">Add</span><span style="color: #008000;">&#40;</span>slave<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: #008000;">&#125;</span>
  ConvertedValue <span style="color: #008000;">=</span> Converter<span style="color: #008000;">.</span><span style="color: #0000FF;">Convert</span><span style="color: #008000;">&#40;</span>values<span style="color: #008000;">.</span><span style="color: #0000FF;">ToArray</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>, <span style="color: #008000;">typeof</span><span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">object</span><span style="color: #008000;">&#41;</span>, ConverterParameter,
    CultureInfo<span style="color: #008000;">.</span><span style="color: #0000FF;">CurrentCulture</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>The ConvertedValue property is bound to the target property of the target element, and will be updated to reflect this change.</p>
<p>This method is very similar to one which Josh Smith described in his codeproject article on the concept of <a href="http://www.codeproject.com/KB/WPF/AttachingVirtualBranches.aspx">Virtual Branches</a>. The MultiBinding and BindingSlave instances can be thought of as a virtual branch to our visual tree: </p>
<p><a href="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2009/06/virtualbranch.png"><img src="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2009/06/virtualbranch.png" alt="virtualbranch" title="virtualbranch" width="604" height="394" class="aligncenter size-full wp-image-355" /></a></p>
<p><strong>Download Sources</strong></p>
<p>You can download the full sourcecode for this project here: <a href='http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2009/06/slmultibinding.zip'>slmultibinding.zip</a></p>
<p><strong>A final word on MVVM</strong></p>
<p>The MVVM pattern is very popular in Silverlight and WPF application development. With this pattern, your view’s DataContext is bound to your view-model. With this pattern in place, the need for multi-bindings can be removed (Josh Smith goes further to moot the concept of <a href="http://joshsmithonwpf.wordpress.com/2008/12/01/the-philosophies-of-mvvm">removing value converters altogether</a>). In our example the PersonViewModel class would simply expose a Title property which performs the same function as the TitleConverter. So does this render my technique completely redundant?</p>
<p>I don’t think so. Whilst MVVM is a great pattern, there are times where adding another layer to your application may be undesirable, especially if your primary aim is simplicity. Furthermore, I do not like being forced into using a specific pattern simply because the framework itself is lacking in functionality. The MVVM pattern is great for building skinnable applications, and allowing UI unit testing, however, if I do not need either of these features, I would prefer not to MVVM.</p>
<p>Regards, Colin E.</p>

]]></content:encoded>
			<wfw:commentRss>http://www.scottlogic.co.uk/blog/colin/2009/06/silverlight-multibindings-how-to-attached-mutiple-bindings-to-a-single-property/feed/</wfw:commentRss>
		<slash:comments>18</slash:comments>
		</item>
		<item>
		<title>Exposing Bindings as Properties of a Control</title>
		<link>http://www.scottlogic.co.uk/blog/colin/2009/06/exposing-bindings-as-properties-of-a-control/</link>
		<comments>http://www.scottlogic.co.uk/blog/colin/2009/06/exposing-bindings-as-properties-of-a-control/#comments</comments>
		<pubDate>Fri, 19 Jun 2009 20:29:35 +0000</pubDate>
		<dc:creator>Colin Eberhardt</dc:creator>
				<category><![CDATA[codeproject]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[binding]]></category>
		<category><![CDATA[silverlight]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://www.scottlogic.co.uk/blog/colin/?p=333</guid>
		<description><![CDATA[I must admit that the title of this post is not entirely clear, however I couldn&#8217;t find a way to sum up the content in one short sentence, so we&#8217;ll dive straight into an example. Let&#8217;s say for example you have developed a funky little business-card as illustrated above, using the simple XAML below: &#60;Border [...]]]></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%252F06%252Fexposing-bindings-as-properties-of-a-control%252F%22%2C%20%22style%22%3A%20%22big%22%2C%20%22title%22%3A%20%22Exposing%20Bindings%20as%20Properties%20of%20a%20Control%20%23%22%20%7D);"></div>
<p><a href="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2009/06/card.png"><img src="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2009/06/card.png" alt="card" title="card" width="228" height="128" class="aligncenter size-full wp-image-336" /></a></p>
<p>I must admit that the title of this post is not entirely clear, however I couldn&#8217;t find a way to sum up the content in one short sentence, so we&#8217;ll dive straight into an example. Let&#8217;s say for example you have developed a funky little business-card as illustrated above, using the simple XAML below:</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;Border</span> <span style="color: #000066;">BorderBrush</span>=<span style="color: #ff0000;">&quot;LightGray&quot;</span> <span style="color: #000066;">Background</span>=<span style="color: #ff0000;">&quot;White&quot;</span>  <span style="color: #000066;">BorderThickness</span>=<span style="color: #ff0000;">&quot;1.5&quot;</span> <span style="color: #000066;">CornerRadius</span>=<span style="color: #ff0000;">&quot;20&quot;</span></span>
<span style="color: #009900;">        <span style="color: #000066;">Width</span>=<span style="color: #ff0000;">&quot;220&quot;</span> <span style="color: #000066;">Height</span>=<span style="color: #ff0000;">&quot;120&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;">Margin</span>=<span style="color: #ff0000;">&quot;5&quot;</span> <span style="color: #000066;">BorderBrush</span>=<span style="color: #ff0000;">&quot;LightGray&quot;</span> <span style="color: #000066;">BorderThickness</span>=<span style="color: #ff0000;">&quot;1.5&quot;</span> <span style="color: #000066;">CornerRadius</span>=<span style="color: #ff0000;">&quot;15&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.Background<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ImageBrush<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ImageBrush.ImageSource<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;BitmapImage</span> <span style="color: #000066;">UriSource</span>=<span style="color: #ff0000;">&quot;back.jpg&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/ImageBrush.ImageSource<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/ImageBrush<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/Border.Background<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;StackPanel</span> <span style="color: #000066;">Orientation</span>=<span style="color: #ff0000;">&quot;Vertical&quot;</span> <span style="color: #000066;">Margin</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;TextBlock</span> <span style="color: #000066;">Text</span>=<span style="color: #ff0000;">&quot;{Binding Name}&quot;</span></span>
<span style="color: #009900;">                       <span style="color: #000066;">FontSize</span>=<span style="color: #ff0000;">&quot;15&quot;</span> <span style="color: #000066;">FontWeight</span>=<span style="color: #ff0000;">&quot;Bold&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Rectangle</span> <span style="color: #000066;">Stroke</span>=<span style="color: #ff0000;">&quot;DarkGray&quot;</span> <span style="color: #000066;">HorizontalAlignment</span>=<span style="color: #ff0000;">&quot;Stretch&quot;</span></span>
<span style="color: #009900;">                       <span style="color: #000066;">StrokeThickness</span>=<span style="color: #ff0000;">&quot;0.5&quot;</span> <span style="color: #000066;">Fill</span>=<span style="color: #ff0000;">&quot;Black&quot;</span> <span style="color: #000066;">Height</span>=<span style="color: #ff0000;">&quot;1&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;TextBlock</span> <span style="color: #000066;">Margin</span>=<span style="color: #ff0000;">&quot;0,10,0,0&quot;</span>  <span style="color: #000066;">Text</span>=<span style="color: #ff0000;">&quot;{Binding Company}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;StackPanel</span> <span style="color: #000066;">Orientation</span>=<span style="color: #ff0000;">&quot;Horizontal&quot;</span> <span style="color: #000000; font-weight: bold;">&gt;</span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;TextBlock</span> <span style="color: #000066;">Text</span>=<span style="color: #ff0000;">&quot;e: &quot;</span> <span style="color: #000066;">FontSize</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;TextBlock</span> <span style="color: #000066;">Text</span>=<span style="color: #ff0000;">&quot;{Binding Email}&quot;</span> <span style="color: #000066;">FontSize</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;/StackPanel<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;StackPanel</span> <span style="color: #000066;">Orientation</span>=<span style="color: #ff0000;">&quot;Horizontal&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;TextBlock</span> <span style="color: #000066;">Text</span>=<span style="color: #ff0000;">&quot;w: &quot;</span> <span style="color: #000066;">FontSize</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;HyperlinkButton</span> <span style="color: #000066;">Content</span>=<span style="color: #ff0000;">&quot;{Binding Web}&quot;</span> <span style="color: #000066;">FontSize</span>=<span style="color: #ff0000;">&quot;10&quot;</span></span>
<span style="color: #009900;">                             <span style="color: #000066;">NavigateUri</span>=<span style="color: #ff0000;">&quot;{Binding Web}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/StackPanel<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/StackPanel<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>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/Border<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>The above XAML creates a simple visual layout that binds to the Name, Email, Web and Company properties of the data object which is presented to the inherited DataContext. Nice and simple.</p>
<p>Now, let&#8217;s say you want to re-use this XAML markup in a number of places across your application. The obvious solution is to package it within a UserControl. However, elsewhere within the application contact details are stored in different types, with different properties, perhaps the property Web is used in some places, whereas the property URL is used elsewhere. If our UserControl simply contains the XAML markup given above, the binding paths are hard-coded and inflexible. So, how do we package the above markup for re-use whilst maintaining flexibility?</p>
<p>In UI frameworks which do not support databinding the obvious choice would be to define an interface IContactDetails, which defines a compile-time contract that clients of the control must implement on their business objects. This would allow us to enforce the presence of properties with specific names. However, with WPF / Silverlight the binding framework removes the need for controls to demand the presence of a certain interface and life is now much better as a result!</p>
<p>So &#8230; what we really want here is to allow the clients of our ContactDetails user control to provide bindings for the various framework elements within the user control itself. </p>
<p>Bindings can be constructed in code-behind by invoking the SetBinding method defined on DependencyObject as show in the example below:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008080; font-style: italic;">// create a binding with a given source and property-path</span>
Binding binding <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Binding<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
binding<span style="color: #008000;">.</span><span style="color: #0000FF;">Source</span> <span style="color: #008000;">=</span> myClass<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: #008000;">new</span> PropertyPath<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;WindowTitle&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008080; font-style: italic;">// bind the button's Content property</span>
button<span style="color: #008000;">.</span><span style="color: #0000FF;">SetBinding</span><span style="color: #008000;">&#40;</span>Button<span style="color: #008000;">.</span><span style="color: #0000FF;">ContentProperty</span>, binding<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>Therefore, if we were to expose the various Bindings as properties of the control (hence this blog post&#8217;s title), we could set the name, email, web elements binding accordingly using the Setbinding method.</p>
<p>The first time I tried this I added a NameBinding dependency property of type Binding to my UserControl, so that the client XAML looked 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;local:ContactDetailsControl</span></span>
<span style="color: #009900;">    <span style="color: #000066;">NameBinding</span>=<span style="color: #ff0000;">&quot;{Binding Name}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span></pre></div></div>

<p>However, this didn&#8217;t quite have the desired effect. When the XAML reader processes the above markup it creates the Binding object that we are after, however it does not set the NameBinding property value to this binding. Instead, it uses it to <em>bind</em> the NameBinding property. </p>
<p>The solution to the problem is to make NameBinding a standard CLR property. This time when the XAML reader encounters the above markup it once again creates the Binding object, but since NameBinding is not a dependency property it does not use it to bind the property, it simply sets the property value.</p>
<p>The code-behind of our ContactDetails user control looks like this:</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;">partial</span> <span style="color: #6666cc; font-weight: bold;">class</span> ContactDetailsControl <span style="color: #008000;">:</span> UserControl
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> Binding NameBinding <span style="color: #008000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> Binding CompanyBinding <span style="color: #008000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> Binding WebBinding <span style="color: #008000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> Binding EmailBinding <span style="color: #008000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">public</span> ContactDetailsControl<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        InitializeComponent<span style="color: #008000;">&#40;</span><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;">private</span> <span style="color: #6666cc; font-weight: bold;">void</span> Border_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>
        nameText<span style="color: #008000;">.</span><span style="color: #0000FF;">SetBinding</span><span style="color: #008000;">&#40;</span>TextBlock<span style="color: #008000;">.</span><span style="color: #0000FF;">TextProperty</span>, NameBinding<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        webText<span style="color: #008000;">.</span><span style="color: #0000FF;">SetBinding</span><span style="color: #008000;">&#40;</span>HyperlinkButton<span style="color: #008000;">.</span><span style="color: #0000FF;">ContentProperty</span>, WebBinding<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        webText<span style="color: #008000;">.</span><span style="color: #0000FF;">SetBinding</span><span style="color: #008000;">&#40;</span>HyperlinkButton<span style="color: #008000;">.</span><span style="color: #0000FF;">NavigateUriProperty</span>, WebBinding<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        companyText<span style="color: #008000;">.</span><span style="color: #0000FF;">SetBinding</span><span style="color: #008000;">&#40;</span>TextBlock<span style="color: #008000;">.</span><span style="color: #0000FF;">TextProperty</span>, CompanyBinding<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        emailText<span style="color: #008000;">.</span><span style="color: #0000FF;">SetBinding</span><span style="color: #008000;">&#40;</span>TextBlock<span style="color: #008000;">.</span><span style="color: #0000FF;">TextProperty</span>, EmailBinding<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>The four bindings are exposed as CLR properties. When the UI is Loaded, we use them to bind the various elements within the control. The net result is that we now have a re-useable control whilst maintaining the flexibility provided by the binding framework, as illustrated by its usage below:</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;local:ContactDetailsControl</span></span>
<span style="color: #009900;">    <span style="color: #000066;">NameBinding</span>=<span style="color: #ff0000;">&quot;{Binding FullName}&quot;</span></span>
<span style="color: #009900;">    <span style="color: #000066;">WebBinding</span>=<span style="color: #ff0000;">&quot;{Binding Website}&quot;</span></span>
<span style="color: #009900;">    <span style="color: #000066;">CompanyBinding</span>=<span style="color: #ff0000;">&quot;{Binding Company}&quot;</span></span>
<span style="color: #009900;">    <span style="color: #000066;">EmailBinding</span>=<span style="color: #ff0000;">&quot;{Binding Email}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span></pre></div></div>

<p>Now for another example and a bit more fun &#8230;</p>
<div id="slPluginHost" > <object id="SilverlightPlugin" width="200" height="200" 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/06/slbindingproperties.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 above Silverlight application shows a number of particles exhibiting <a href="http://en.wikipedia.org/wiki/Brownian_motion">Brownian motion</a>. </p>
<p>This application creates 50 instances of a Particle object within an ObservableCollection:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #6666cc; font-weight: bold;">class</span> Particle <span style="color: #008000;">:</span> INotifyPropertyChanged
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">double</span> XLocation <span style="color: #008000;">&#123;</span> <span style="color: #008000;">...</span> <span style="color: #008000;">&#125;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">double</span> YLocation <span style="color: #008000;">&#123;</span> <span style="color: #008000;">...</span> <span style="color: #008000;">&#125;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">double</span> Excitement <span style="color: #008000;">&#123;</span> <span style="color: #008000;">...</span> <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>The particles are rendered by a ScatterControl, which is a UserControl:</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;Border</span> <span style="color: #000066;">BorderBrush</span>=<span style="color: #ff0000;">&quot;LightGray&quot;</span> <span style="color: #000066;">BorderThickness</span>=<span style="color: #ff0000;">&quot;1&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #808080; font-style: italic;">&lt;!-- ItemsSource property set in code-behind --&gt;</span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;local:ScatterControl</span> <span style="color: #000066;">x:Name</span>=<span style="color: #ff0000;">&quot;scatterControl&quot;</span></span>
<span style="color: #009900;">                      <span style="color: #000066;">XValueBinding</span>=<span style="color: #ff0000;">&quot;{Binding Path=XLocation}&quot;</span></span>
<span style="color: #009900;">                      <span style="color: #000066;">YValueBinding</span>=<span style="color: #ff0000;">&quot;{Binding Path=YLocation}&quot;</span></span>
<span style="color: #009900;">                      <span style="color: #000066;">FillBinding</span>=<span style="color: #ff0000;">&quot;{Binding Path=Excitement,</span>
<span style="color: #009900;">                            Converter={StaticResource FillConverter}}&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 style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>This control has an ItemsSource property of type IEnumerable, and exposes three other properties of type Binding.</p>
<p>The markup for this control is given below:</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;UserControl</span> ... <span style="color: #000000; font-weight: bold;">&gt;</span></span>
&nbsp;
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ItemsControl</span> <span style="color: #000066;">x:Name</span>=<span style="color: #ff0000;">&quot;itemsControl&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ItemsControl.ItemsPanel<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ItemsPanelTemplate<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Canvas</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/ItemsPanelTemplate<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/ItemsControl.ItemsPanel<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ItemsControl.ItemTemplate<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;Canvas<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Ellipse</span> <span style="color: #000066;">Width</span>=<span style="color: #ff0000;">&quot;10&quot;</span> <span style="color: #000066;">Height</span>=<span style="color: #ff0000;">&quot;10&quot;</span> <span style="color: #000066;">Fill</span>=<span style="color: #ff0000;">&quot;Red&quot;</span></span>
<span style="color: #009900;">                             <span style="color: #000066;">Loaded</span>=<span style="color: #ff0000;">&quot;Ellipse_Loaded&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/Canvas<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;/ItemsControl.ItemTemplate<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/ItemsControl<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>    
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/UserControl<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>The particles are rendered using an ItemsControl, which creates an instance of an Ellipse for each bound particle and places it within a Canvas (As defined by the ItemsControl.ItemsPanel property). As each ellipse is loaded, we set the bindings in code-behind:</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> Ellipse_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>
    Ellipse ellipse <span style="color: #008000;">=</span> sender <span style="color: #0600FF; font-weight: bold;">as</span> Ellipse<span style="color: #008000;">;</span>
    ellipse<span style="color: #008000;">.</span><span style="color: #0000FF;">SetBinding</span><span style="color: #008000;">&#40;</span>Canvas<span style="color: #008000;">.</span><span style="color: #0000FF;">LeftProperty</span>, XValueBinding<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    ellipse<span style="color: #008000;">.</span><span style="color: #0000FF;">SetBinding</span><span style="color: #008000;">&#40;</span>Canvas<span style="color: #008000;">.</span><span style="color: #0000FF;">TopProperty</span>, YValueBinding<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    ellipse<span style="color: #008000;">.</span><span style="color: #0000FF;">SetBinding</span><span style="color: #008000;">&#40;</span>Ellipse<span style="color: #008000;">.</span><span style="color: #0000FF;">FillProperty</span>, FillBinding<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Again, by exposing Bindings as properties this user control is just as flexible as if its markup was included in the page directly. This example also illustrates another interesting point, the Bindings that the client provided have been re-used for each Ellipse that was created by the ItemsControl. This is made possible because when SetBinding is invoked on our Ellipse, the Binding is not associated with the Ellipse, rather, it is used to create an instance of a <a href="http://msdn.microsoft.com/en-us/library/system.windows.data.bindingexpression(VS.85).aspx">BindingExpression</a>. Binding is used to declare a binding, whereas BindingExpression is the implementation, i.e. it does the heavy-lifting of copying data to-and-from from source to target (and vice-versa).</p>
<p>You can download the full source for both examples: <a href='http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2009/06/bindingproperties.zip'>bindingproperties.zip</a></p>
<p>Regards, Colin E.</p>

]]></content:encoded>
			<wfw:commentRss>http://www.scottlogic.co.uk/blog/colin/2009/06/exposing-bindings-as-properties-of-a-control/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>

