<?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; WPF</title>
	<atom:link href="http://www.scottlogic.co.uk/blog/colin/category/wpf/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 Universal Value Converter for WPF</title>
		<link>http://www.scottlogic.co.uk/blog/colin/2010/07/a-universal-value-converter-for-wpf/</link>
		<comments>http://www.scottlogic.co.uk/blog/colin/2010/07/a-universal-value-converter-for-wpf/#comments</comments>
		<pubDate>Fri, 09 Jul 2010 11:33:18 +0000</pubDate>
		<dc:creator>Colin Eberhardt</dc:creator>
				<category><![CDATA[codeproject]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[valueconverter]]></category>

		<guid isPermaLink="false">http://www.scottlogic.co.uk/blog/colin/?p=726</guid>
		<description><![CDATA[This post provides a simple IValueConverter implementation that makes use of the framework type converters in order to convert between a large range of source / target types. This converter can be used both within bindings and in code-behind to give more concise property setters. Introduction One of the great features of the XAML language [...]]]></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%252F07%252Fa-universal-value-converter-for-wpf%252F%22%2C%20%22style%22%3A%20%22big%22%2C%20%22title%22%3A%20%22A%20Universal%20Value%20Converter%20for%20WPF%20%23%22%20%7D);"></div>
<p><em>This post provides a simple IValueConverter implementation that makes use of the framework type converters in order to convert between a large range of source / target types. This converter can be used both within bindings and in code-behind to give more concise property setters.</em></p>
<h2>Introduction</h2>
<p>One of the great features of the XAML language is that it is flexible, concise and expressive (yes, I know that XML can be a little verbose, but if you try to create a complex UI purely in code-behind I think you will agree with my observations!). For example, you can set the fill of a rectangle by simply specifying the named color:</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;Rectangle</span> <span style="color: #000066;">Fill</span>=<span style="color: #ff0000;">&quot;Green&quot;</span>/<span style="color: #66cc66;">&#41;</span></span></pre></div></div>

<p>or &#8230; you can specify the RGB values directly:</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;Rectangle</span> <span style="color: #000066;">Fill</span>=<span style="color: #ff0000;">&quot;#00FF00&quot;</span>/<span style="color: #66cc66;">&#41;</span></span></pre></div></div>

<p>Looking at the above examples, you might be fooled into thinking that the Fill property is of type Color. People who are new to WPF often find that this is not the case the first time they try to bind a property of type Color to the Fill property (they would never set the Fill property directly in code behind, because that would be a cardinal sin!). The Fill property is actually of type Brush, and the XAML parser is performing some cunning type conversions in order to make the above markup work.</p>
<p>The solution to this problem of binding a Color to the Fill property is to create a 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> ColorToBrushConverter <span style="color: #008000;">:</span> IValueConverter
<span style="color: #008000;">&#123;</span>
  <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">object</span> Convert<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">object</span> value, Type targetType, <span style="color: #6666cc; font-weight: bold;">object</span> parameter, CultureInfo culture<span style="color: #008000;">&#41;</span>
  <span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>value <span style="color: #008000;">is</span> Color<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> SolidColorBrush<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#40;</span>Color<span style="color: #008000;">&#41;</span>value<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
    <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">;</span>
  <span style="color: #008000;">&#125;</span>
&nbsp;
  <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">object</span> ConvertBack<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">object</span> value, Type targetType, <span style="color: #6666cc; font-weight: bold;">object</span> parameter, CultureInfo culture<span style="color: #008000;">&#41;</span>
  <span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">throw</span> <span style="color: #008000;">new</span> Exception<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;The method or operation is not implemented.&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></pre></div></div>

<p>Which can be used 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;Rectangle</span> <span style="color: #000066;">Fill</span>=<span style="color: #ff0000;">&quot;{Binding Path=MyColorProperty,</span>
<span style="color: #009900;">                                  Converter={StaticResource ColorToBrushConverter}} &quot;</span>/<span style="color: #66cc66;">&#41;</span></span></pre></div></div>

<p>If you search google for <a href="http://www.google.co.uk/search?q=colortobrushconverter">ColorToBrushConverter</a>, you can see that there are a great many people who have implemented this simple little converter. But what happens if you want to bind to a string representation of color? or you want to bind to a stroke dash property or path geometry? Whilst value converters are simple to implement, it is a shame that you have to create so many of them!</p>
<h2>A Universal Value Converter</h2>
<p><img src="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2010/07/816000_pocket_knife.jpg" alt="" title="816000_pocket_knife" width="300" height="199" class="aligncenter size-full wp-image-728" /></p>
<p>Wouldn&#8217;t it be great to have a single value converter that has the same flexibility as the XAML parser? It is actually very simple to create such as converter (and after creating probably my 5th ColorToBrushConverter I have no idea why it took so long before I realised this!). The .NET framework has had an API for conversion between different types via <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.typeconverter.aspx">TypeConverters</a> for a long time. They used extensively in .NET technologies for databinding and designer support, and much more.</p>
<p>A value converter can obtain a suitable TypeConverter for the target property then perform the required conversion:</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> UniversalValueConverter <span style="color: #008000;">:</span> IValueConverter
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">object</span> Convert<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">object</span> value, Type targetType, <span style="color: #6666cc; font-weight: bold;">object</span> parameter, CultureInfo culture<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #008080; font-style: italic;">// obtain the conveter for the target type</span>
        TypeConverter converter <span style="color: #008000;">=</span> TypeDescriptor<span style="color: #008000;">.</span><span style="color: #0000FF;">GetConverter</span><span style="color: #008000;">&#40;</span>targetType<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #0600FF; font-weight: bold;">try</span>
        <span style="color: #008000;">&#123;</span>
            <span style="color: #008080; font-style: italic;">// determine if the supplied value is of a suitable type</span>
            <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>converter<span style="color: #008000;">.</span><span style="color: #0000FF;">CanConvertFrom</span><span style="color: #008000;">&#40;</span>value<span style="color: #008000;">.</span><span style="color: #0000FF;">GetType</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
            <span style="color: #008000;">&#123;</span>
                <span style="color: #008080; font-style: italic;">// return the converted value</span>
                <span style="color: #0600FF; font-weight: bold;">return</span> converter<span style="color: #008000;">.</span><span style="color: #0000FF;">ConvertFrom</span><span style="color: #008000;">&#40;</span>value<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #008000;">&#125;</span>
            <span style="color: #0600FF; font-weight: bold;">else</span>
            <span style="color: #008000;">&#123;</span>
                <span style="color: #008080; font-style: italic;">// try to convert from the string representation</span>
                <span style="color: #0600FF; font-weight: bold;">return</span> converter<span style="color: #008000;">.</span><span style="color: #0000FF;">ConvertFrom</span><span style="color: #008000;">&#40;</span>value<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;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #008000;">&#125;</span>
        <span style="color: #008000;">&#125;</span>
        <span style="color: #0600FF; font-weight: bold;">catch</span> <span style="color: #008000;">&#40;</span>Exception<span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            <span style="color: #0600FF; font-weight: bold;">return</span> value<span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">object</span> ConvertBack<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">object</span> value, Type targetType, <span style="color: #6666cc; font-weight: bold;">object</span> parameter, CultureInfo culture<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">throw</span> <span style="color: #008000;">new</span> NotImplementedException<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Note, that this value converter first tries to convert directly from the source to the target type, if this is not possible it then tried to convert via a string representation (I am not sure whether it is more correct to obtain a TypeConverter for the String type, then use this rather that invoking ToString on the value being converted, but the above works for me <img src='http://www.scottlogic.co.uk/blog/colin/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' />  ).</p>
<p>You can see this converter in action below where a range of type conversions are demonstrated:</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;Converting String to Brush ....&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;">Fill</span>=<span style="color: #ff0000;">&quot;{Binding ElementName=colorTextBox, Path=Text, Converter={StaticResource UniversalValueConverter}}&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;">x:Name</span>=<span style="color: #ff0000;">&quot;colorTextBox&quot;</span></span>
<span style="color: #009900;">             <span style="color: #000066;">Text</span>=<span style="color: #ff0000;">&quot;Red&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;Converting String to Geometry ....&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Path</span> <span style="color: #000066;">Data</span>=<span style="color: #ff0000;">&quot;{Binding ElementName=geometryText, Path=Text, Converter={StaticResource UniversalValueConverter}}&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;">x:Name</span>=<span style="color: #ff0000;">&quot;geometryText&quot;</span>                  </span>
<span style="color: #009900;">             <span style="color: #000066;">Text</span>=<span style="color: #ff0000;">&quot;M 10,20 C 10,2.5 40,35 40,17 H 28&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;Converting String to DoubleCollection (stroke dash) ....&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;">StrokeDashArray</span>=<span style="color: #ff0000;">&quot;{Binding ElementName=dashText, Path=Text, Converter={StaticResource UniversalValueConverter}}&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;">x:Name</span>=<span style="color: #ff0000;">&quot;dashText&quot;</span>                  </span>
<span style="color: #009900;">            <span style="color: #000066;">Text</span>=<span style="color: #ff0000;">&quot;2 2 4 5&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span></pre></div></div>

<p><img src="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2010/07/universal.png" alt="" title="universal" width="395" height="345" class="aligncenter size-full wp-image-735" /></p>
<p>For the first conversion, string to brush, you can use named colors, and the hex notation in its range of abbreviated forms (#AF7, #AAFF77, #FFAAFF77 &#8230;). You can also use this converter to convert from string to their corresponding enum values, for example binding the string &#8220;Collapsed&#8221; to the Visbility property.</p>
<h2>Value conversion in code behind</h2>
<p>The above converter really is swiss army knife for bindings, but what about code-behind? You are still constrained by the type requirements of the property being set:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">rect1<span style="color: #008000;">.</span><span style="color: #0000FF;">Fill</span> <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> SolidColorBrush<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    Color <span style="color: #008000;">=</span> Colors<span style="color: #008000;">.</span><span style="color: #0000FF;">Red</span>
<span style="color: #008000;">&#125;</span><span style="color: #008000;">;</span></pre></div></div>

<p>Value converters, whilst typically used in binding, can also be used directly in code-behind. The following extension method extends <code>SetValue</code> method for setting dependency properties to make use of the above value 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;">/// Sets the given dependency property, applying type conversion where required</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: #6666cc; font-weight: bold;">void</span> SetValueEx<span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">this</span> DependencyObject element, DependencyProperty property, <span style="color: #6666cc; font-weight: bold;">object</span> value<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    var conv <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> UniversalValueConverter<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    var convertedValue <span style="color: #008000;">=</span> conv<span style="color: #008000;">.</span><span style="color: #0000FF;">Convert</span><span style="color: #008000;">&#40;</span>value, property<span style="color: #008000;">.</span><span style="color: #0000FF;">PropertyType</span>, <span style="color: #0600FF; font-weight: bold;">null</span>, CultureInfo<span style="color: #008000;">.</span><span style="color: #0000FF;">InvariantCulture</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    element<span style="color: #008000;">.</span><span style="color: #0000FF;">SetValue</span><span style="color: #008000;">&#40;</span>property, convertedValue<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Which provides a more flexible mechanism for setting property values:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">rect1<span style="color: #008000;">.</span><span style="color: #0000FF;">SetValueEx</span><span style="color: #008000;">&#40;</span>Rectangle<span style="color: #008000;">.</span><span style="color: #0000FF;">FillProperty</span>, Colors<span style="color: #008000;">.</span><span style="color: #0000FF;">Red</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
rect2<span style="color: #008000;">.</span><span style="color: #0000FF;">SetValueEx</span><span style="color: #008000;">&#40;</span>Rectangle<span style="color: #008000;">.</span><span style="color: #0000FF;">FillProperty</span>, <span style="color: #666666;">&quot;Blue&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
rect3<span style="color: #008000;">.</span><span style="color: #0000FF;">SetValueEx</span><span style="color: #008000;">&#40;</span>Rectangle<span style="color: #008000;">.</span><span style="color: #0000FF;">FillProperty</span>, <span style="color: #666666;">&quot;#FFEE55&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
rect4<span style="color: #008000;">.</span><span style="color: #0000FF;">SetValueEx</span><span style="color: #008000;">&#40;</span>Rectangle<span style="color: #008000;">.</span><span style="color: #0000FF;">FillProperty</span>, <span style="color: #008000;">new</span> SolidColorBrush<span style="color: #008000;">&#40;</span>Colors<span style="color: #008000;">.</span><span style="color: #0000FF;">Orange</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<h2>&#8230; and Silverlight?</h2>
<p>Unfortunately Silverlight lacks the TypeDescriptor class which is used to obtain TypeConveters. I am guessing that type conversion within Silverlight is &#8216;baked-in&#8217; to the XAML parser, which means that it is not possible to re-use this logic <img src='http://www.scottlogic.co.uk/blog/colin/wp-includes/images/smilies/icon_sad.gif' alt=':-(' class='wp-smiley' /> </p>
<p>You can download the full source for this blog post: <a href='http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2010/07/UniversalValueConverter.zip'>UniversalValueConverter.zip</a></p>
<p>Regards,<br />
Colin E.</p>

]]></content:encoded>
			<wfw:commentRss>http://www.scottlogic.co.uk/blog/colin/2010/07/a-universal-value-converter-for-wpf/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>Implementing RelativeSource binding in Silverlight</title>
		<link>http://www.scottlogic.co.uk/blog/colin/2009/02/relativesource-binding-in-silverlight/</link>
		<comments>http://www.scottlogic.co.uk/blog/colin/2009/02/relativesource-binding-in-silverlight/#comments</comments>
		<pubDate>Fri, 27 Feb 2009 14:57:35 +0000</pubDate>
		<dc:creator>Colin Eberhardt</dc:creator>
				<category><![CDATA[codeproject]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[attached behaviour]]></category>
		<category><![CDATA[binding]]></category>
		<category><![CDATA[silverlight]]></category>

		<guid isPermaLink="false">http://www.scottlogic.co.uk/blog/colin/?p=139</guid>
		<description><![CDATA[In my previous post I demonstrated how an the WPF ElementName style binding can be emulated with Silverlight via an attached behaviour. As a brief recap, the technique involved creating an attached property, which when bound, adds a handler for the elements Loaded event. When the element is loaded, the even handler locates the named [...]]]></description>
			<content:encoded><![CDATA[
<div class="topsy_widget_data topsy_theme_light-green" style="float: right;margin-left: 0.75em; background: url(data:,%7B%20%22url%22%3A%20%22http%253A%252F%252Fwww.scottlogic.co.uk%252Fblog%252Fcolin%252F2009%252F02%252Frelativesource-binding-in-silverlight%252F%22%2C%20%22style%22%3A%20%22big%22%2C%20%22title%22%3A%20%22Implementing%20RelativeSource%20binding%20in%20Silverlight%20%23%22%20%7D);"></div>
<p>In my <a href="http://www.scottlogic.co.uk/blog/colin/2009/02/elementname-binding-in-silverlight-via-attached-behaviours/">previous post</a> I demonstrated how an the WPF ElementName style binding can be emulated with Silverlight via an attached behaviour. As a brief recap, the technique involved creating an attached property, which when bound, adds a handler for the elements Loaded event. When the element is loaded, the even handler locates the named element and constructs a binding via a relay object. Here is the attached property in use:</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;Rectangle</span> <span style="color: #000066;">Height</span>=<span style="color: #ff0000;">&quot;20&quot;</span> <span style="color: #000066;">Fill</span>=<span style="color: #ff0000;">&quot;Green&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;local:BindingHelper.Binding<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;local:BindingProperties</span> <span style="color: #000066;">ElementName</span>=<span style="color: #ff0000;">&quot;Slider&quot;</span> <span style="color: #000066;">SourceProperty</span>=<span style="color: #ff0000;">&quot;Value&quot;</span> <span style="color: #000066;">TargetProperty</span>=<span style="color: #ff0000;">&quot;Width&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:BindingHelper.Binding<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/Rectangle<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<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;Slider&quot;</span> <span style="color: #000066;">Value</span>=<span style="color: #ff0000;">&quot;20&quot;</span> <span style="color: #000066;">Minimum</span>=<span style="color: #ff0000;">&quot;0&quot;</span> <span style="color: #000066;">Maximum</span>=<span style="color: #ff0000;">&quot;300&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span></pre></div></div>

<p>Where the Rectangle&#8217;s Width is bound to the Slider&#8217;s Value. For details, and sourcecode, visit <a href="http://www.scottlogic.co.uk/blog/colin/2009/02/elementname-binding-in-silverlight-via-attached-behaviours/">this blog post</a>. Here I am going to extend this attached behaviour in order to emulate WPF&#8217;s RelativeSource binding.</p>
<p>For much of the time you will want to bind your visual elements to your data objects via their DataContext property. However, there are often times when you want too perform a binding for pure presentation purposes, for example, binding the width of two elements together. In this context WPFs RelativeSource and ElementName binding prove to be powerful and useful features of the binding framework.</p>
<p>Here I will extend the attached behaviour I described in my previous post to add RelativeSource binding capabilities. The properties of the attached property type have been extended:</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> BindingProperties
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">string</span> SourceProperty <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> <span style="color: #6666cc; font-weight: bold;">string</span> ElementName <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> <span style="color: #6666cc; font-weight: bold;">string</span> TargetProperty <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> IValueConverter Converter <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> <span style="color: #6666cc; font-weight: bold;">object</span> ConverterParameter <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> <span style="color: #6666cc; font-weight: bold;">bool</span> RelativeSourceSelf <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> <span style="color: #6666cc; font-weight: bold;">string</span> RelativeSourceAncestorType <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> <span style="color: #6666cc; font-weight: bold;">int</span> RelativeSourceAncestorLevel <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> BindingProperties<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        RelativeSourceAncestorLevel <span style="color: #008000;">=</span> <span style="color: #FF0000;">1</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>With the RelativeSourceSelf, RelativeSourceAncestorType and RelativeSourceAncestorLevel properties being used for relative source bindings. Taking RelativeSourceSelf as our first example, within WPF a <a href="http://msdn.microsoft.com/en-us/library/system.windows.data.relativesource.self.aspx">RelativeSource.Self</a> property indicates that the source of a binding should be the element which the binding is associated with. (I know &#8211; it sounds a bit crazy, but search <a href="http://www.google.co.uk/search?q=RelativeSource+Self">google</a>, it is surprisingly useful!).</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> OnBinding<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;
    targetElement<span style="color: #008000;">.</span><span style="color: #0000FF;">Loaded</span> <span style="color: #008000;">+=</span> <span style="color: #008000;">new</span> RoutedEventHandler<span style="color: #008000;">&#40;</span>TargetElement_Loaded<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: #0600FF; font-weight: bold;">static</span> <span style="color: #6666cc; font-weight: bold;">void</span> TargetElement_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>
    FrameworkElement targetElement <span style="color: #008000;">=</span> sender <span style="color: #0600FF; font-weight: bold;">as</span> FrameworkElement<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">// get the value of our attached property</span>
    BindingProperties bindingProperties <span style="color: #008000;">=</span> GetBinding<span style="color: #008000;">&#40;</span>targetElement<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>bindingProperties<span style="color: #008000;">.</span><span style="color: #0000FF;">ElementName</span> <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;">// perform our 'ElementName' lookup</span>
        <span style="color: #008000;">...</span>
    <span style="color: #008000;">&#125;</span>
    <span style="color: #0600FF; font-weight: bold;">else</span> <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>bindingProperties<span style="color: #008000;">.</span><span style="color: #0000FF;">RelativeSourceSelf</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #008080; font-style: italic;">// bind an element to itself.</span>
        CreateRelayBinding<span style="color: #008000;">&#40;</span>targetElement, targetElement, bindingProperties<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>When the attached property becomes attached to our target element it adds a handler for the elements Loaded event (this is the <em>attached behaviour</em>). Within the event handler, we determine whether this is a relative source binding. If this is the case, the CreateRelayBinding method is invoked where the source and target element parameters are the same element. For details of how the CreateRelayBinding method works, see the <a href="http://www.scottlogic.co.uk/blog/colin/2009/02/elementname-binding-in-silverlight-via-attached-behaviours/">previous blog post</a>.  An example of a relative-source self binding is show below, where a TextBox&#8217;s Width property is bound to its Text, if you trype in a new text value, the TextBox Width adjusts accordingly.</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;TextBox</span> <span style="color: #000066;">Text</span>=<span style="color: #ff0000;">&quot;200&quot;</span> <span style="color: #000066;">Margin</span>=<span style="color: #ff0000;">&quot;0,5,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:BindingHelper.Binding<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;local:BindingProperties</span> <span style="color: #000066;">TargetProperty</span>=<span style="color: #ff0000;">&quot;Width&quot;</span> <span style="color: #000066;">SourceProperty</span>=<span style="color: #ff0000;">&quot;Text&quot;</span></span>
<span style="color: #009900;">                                 <span style="color: #000066;">RelativeSourceSelf</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;/local:BindingHelper.Binding<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>The next type of RelativeSource binding I am going to tackle is the FindAncestor mode. You use this type of binding when you want to bind to an element of a specific type that is located further up the visual tree that the target element. The following code snippet shows how the attached behaviour achieves this type of binding:</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> TargetElement_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>
    FrameworkElement targetElement <span style="color: #008000;">=</span> sender <span style="color: #0600FF; font-weight: bold;">as</span> FrameworkElement<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">// get the value of our attached property</span>
    BindingProperties bindingProperties <span style="color: #008000;">=</span> GetBinding<span style="color: #008000;">&#40;</span>targetElement<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>bindingProperties<span style="color: #008000;">.</span><span style="color: #0000FF;">ElementName</span> <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;">// perform our 'ElementName' lookup</span>
        <span style="color: #008000;">...</span>
    <span style="color: #008000;">&#125;</span>
    <span style="color: #0600FF; font-weight: bold;">else</span> <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>bindingProperties<span style="color: #008000;">.</span><span style="color: #0000FF;">RelativeSourceSelf</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #008080; font-style: italic;">// bind an element to itself.</span>
        <span style="color: #008000;">...</span>
    <span style="color: #008000;">&#125;</span>
    <span style="color: #0600FF; font-weight: bold;">else</span> <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span><span style="color: #008000;">!</span><span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">.</span><span style="color: #0000FF;">IsNullOrEmpty</span><span style="color: #008000;">&#40;</span>bindingProperties<span style="color: #008000;">.</span><span style="color: #0000FF;">RelativeSourceAncestorType</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">// navigate up the tree to find the type</span>
        DependencyObject currentObject <span style="color: #008000;">=</span> targetElement<span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #6666cc; font-weight: bold;">int</span> currentLevel <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF; font-weight: bold;">while</span> <span style="color: #008000;">&#40;</span>currentLevel <span style="color: #008000;">&lt;</span> bindingProperties<span style="color: #008000;">.</span><span style="color: #0000FF;">RelativeSourceAncestorLevel</span><span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            <span style="color: #0600FF; font-weight: bold;">do</span>
            <span style="color: #008000;">&#123;</span>
                currentObject <span style="color: #008000;">=</span> VisualTreeHelper<span style="color: #008000;">.</span><span style="color: #0000FF;">GetParent</span><span style="color: #008000;">&#40;</span>currentObject<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #008000;">&#125;</span>
            <span style="color: #0600FF; font-weight: bold;">while</span> <span style="color: #008000;">&#40;</span>currentObject<span style="color: #008000;">.</span><span style="color: #0000FF;">GetType</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Name</span> <span style="color: #008000;">!=</span> bindingProperties<span style="color: #008000;">.</span><span style="color: #0000FF;">RelativeSourceAncestorType</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            currentLevel<span style="color: #008000;">++;</span>
        <span style="color: #008000;">&#125;</span>
&nbsp;
        FrameworkElement sourceElement <span style="color: #008000;">=</span> currentObject <span style="color: #0600FF; font-weight: bold;">as</span> FrameworkElement<span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">// bind them</span>
        CreateRelayBinding<span style="color: #008000;">&#40;</span>targetElement, sourceElement, bindingProperties<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 code above simply navigates up the visual tree to find the n&#8217;th element of a given type. When the given type has been located, the relay binding between the two is constructed.</p>
<p>This type of binding is incredibly flexible, the following shows a number of examples:</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;SilverlightBinding.PageTwo&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;UserControl.Resources<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;local:VisibilityConverter</span> <span style="color: #000066;">x:Key</span>=<span style="color: #ff0000;">&quot;VisibilityConverter&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/UserControl.Resources<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;StackPanel</span> <span style="color: #000066;">x:Name</span>=<span style="color: #ff0000;">&quot;TheOuterStackPanel&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;StackPanel</span> <span style="color: #000066;">Name</span>=<span style="color: #ff0000;">&quot;theInnerStackPanel&quot;</span> <span style="color: #000066;">Width</span>=<span style="color: #ff0000;">&quot;400&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
            <span style="color: #808080; font-style: italic;">&lt;!-- bind the textbox width to its text property --&gt;</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;200&quot;</span> <span style="color: #000066;">Margin</span>=<span style="color: #ff0000;">&quot;0,5,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:BindingHelper.Binding<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;local:BindingProperties</span> <span style="color: #000066;">TargetProperty</span>=<span style="color: #ff0000;">&quot;Width&quot;</span> <span style="color: #000066;">SourceProperty</span>=<span style="color: #ff0000;">&quot;Text&quot;</span></span>
<span style="color: #009900;">                                             <span style="color: #000066;">RelativeSourceSelf</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;/local:BindingHelper.Binding<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>
            <span style="color: #808080; font-style: italic;">&lt;!-- bind the textbox text to this UserControls width property --&gt;</span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;TextBox</span> <span style="color: #000066;">Margin</span>=<span style="color: #ff0000;">&quot;0,5,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:BindingHelper.Binding<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;local:BindingProperties</span> <span style="color: #000066;">TargetProperty</span>=<span style="color: #ff0000;">&quot;Text&quot;</span> <span style="color: #000066;">SourceProperty</span>=<span style="color: #ff0000;">&quot;Width&quot;</span></span>
<span style="color: #009900;">                                             <span style="color: #000066;">RelativeSourceAncestorType</span>=<span style="color: #ff0000;">&quot;PageTwo&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:BindingHelper.Binding<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>
            <span style="color: #808080; font-style: italic;">&lt;!-- bind the textbox text to the inner stack panels name property --&gt;</span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;TextBox</span> <span style="color: #000066;">Margin</span>=<span style="color: #ff0000;">&quot;0,5,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:BindingHelper.Binding<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;local:BindingProperties</span> <span style="color: #000066;">TargetProperty</span>=<span style="color: #ff0000;">&quot;Text&quot;</span> <span style="color: #000066;">SourceProperty</span>=<span style="color: #ff0000;">&quot;Name&quot;</span></span>
<span style="color: #009900;">                                             <span style="color: #000066;">RelativeSourceAncestorType</span>=<span style="color: #ff0000;">&quot;StackPanel&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:BindingHelper.Binding<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>
            <span style="color: #808080; font-style: italic;">&lt;!-- bind the textbox text to the outer stack panels name property --&gt;</span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;TextBox</span> <span style="color: #000066;">Margin</span>=<span style="color: #ff0000;">&quot;0,5,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:BindingHelper.Binding<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;local:BindingProperties</span> <span style="color: #000066;">TargetProperty</span>=<span style="color: #ff0000;">&quot;Text&quot;</span> <span style="color: #000066;">SourceProperty</span>=<span style="color: #ff0000;">&quot;Name&quot;</span></span>
<span style="color: #009900;">                                             <span style="color: #000066;">RelativeSourceAncestorType</span>=<span style="color: #ff0000;">&quot;StackPanel&quot;</span></span>
<span style="color: #009900;">                                             <span style="color: #000066;">RelativeSourceAncestorLevel</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:BindingHelper.Binding<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>
            <span style="color: #808080; font-style: italic;">&lt;!-- bind a slider's value to its parent grid's height property  --&gt;</span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Grid</span> <span style="color: #000066;">Height</span>=<span style="color: #ff0000;">&quot;30&quot;</span>  <span style="color: #000066;">Margin</span>=<span style="color: #ff0000;">&quot;0,5,0,0&quot;</span> <span style="color: #000066;">Background</span>=<span style="color: #ff0000;">&quot;CadetBlue&quot;</span> <span style="color: #000066;">HorizontalAlignment</span>=<span style="color: #ff0000;">&quot;Left&quot;</span> <span style="color: #000000; font-weight: bold;">&gt;</span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Slider</span> <span style="color: #000066;">Width</span>=<span style="color: #ff0000;">&quot;400&quot;</span>  <span style="color: #000066;">HorizontalAlignment</span>=<span style="color: #ff0000;">&quot;Left&quot;</span> <span style="color: #000066;">Minimum</span>=<span style="color: #ff0000;">&quot;10&quot;</span> <span style="color: #000066;">Maximum</span>=<span style="color: #ff0000;">&quot;40&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:BindingHelper.Binding<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;local:BindingProperties</span> <span style="color: #000066;">TargetProperty</span>=<span style="color: #ff0000;">&quot;Value&quot;</span> <span style="color: #000066;">SourceProperty</span>=<span style="color: #ff0000;">&quot;Height&quot;</span></span>
<span style="color: #009900;">                                             <span style="color: #000066;">RelativeSourceAncestorType</span>=<span style="color: #ff0000;">&quot;Grid&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:BindingHelper.Binding<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/Slider<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;/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;/UserControl<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>You can see in the above XAML, examples of relative-source self and find ancestor bindings with a variety of types and ancestor-levels. And here it is in action:</p>
<div id="slPluginHost"> <object id="SilverlightPlugin" width="400" 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/02/silverlightbinding2.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>If you type in a new value in the top text box its width will change, or move the slider to see the height of its parent grid changing. And all without any code-behind of course!</p>
<p>Many of these effects shown above could be performed via element-name bindings. However, you are not always the creator, or template provider for all the visual elements rendered to screen. One common example is that of the ItemsControl, the ListBox being an example of this type of control. Here you supply a DataTemplate, with your visual elements being rendered inside a ListBoxItem container. Therefore, there is no way to bind to the ListBoxItem via an element name or otherwise. However, you can reach the ListBoxItem by navigating up the tree using a relative-source binding as 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;ListBox</span> <span style="color: #000066;">Name</span>=<span style="color: #ff0000;">&quot;grid&quot;</span> <span style="color: #000066;">Width</span>=<span style="color: #ff0000;">&quot;200&quot;</span> <span style="color: #000066;">HorizontalAlignment</span>=<span style="color: #ff0000;">&quot;Left&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ListBox.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;Grid</span> <span style="color: #000066;">Width</span>=<span style="color: #ff0000;">&quot;180&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 Forename}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;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 style="color: #000066;">HorizontalAlignment</span>=<span style="color: #ff0000;">&quot;Right&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:BindingHelper.Binding<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;local:BindingProperties</span> <span style="color: #000066;">TargetProperty</span>=<span style="color: #ff0000;">&quot;Visibility&quot;</span> <span style="color: #000066;">SourceProperty</span>=<span style="color: #ff0000;">&quot;IsSelected&quot;</span></span>
<span style="color: #009900;">                                                 <span style="color: #000066;">Converter</span>=<span style="color: #ff0000;">&quot;{StaticResource VisibilityConverter}&quot;</span></span>
<span style="color: #009900;">                                                 <span style="color: #000066;">RelativeSourceAncestorType</span>=<span style="color: #ff0000;">&quot;ListBoxItem&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:BindingHelper.Binding<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 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;/DataTemplate<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/ListBox.ItemTemplate<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/ListBox<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>In the above example we have a DataTemplate which contains an ellipse. As the ListBox generates each &#8216;row&#8217;, it creates a ListBoxItem and populates it with the visual elements from our data template. When our ellipse is created, and loaded, the attached behaviour fires, navigating up the visual tree to find the first ListBoxItem it encounters. When it finds it, it creates a single instance of our relay object, binding both the ListBoxItem.IsSelected and Ellipse.Visibilty (via a suitable value converter) together via the relay object.</p>
<p>And here it is in action (click an item to see the ellipse) &#8230;</p>
<div id="slPluginHost"> <object id="SilverlightPlugin" width="400" 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/02/silverlightbinding1.xap"/><a href="http://go.microsoft.com/fwlink/?LinkID=124807"  style="text-decoration: none;"> <img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style: none"/></a></object></div>
<p>You can download a visual studio project with all the sourcecode: <a href='http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2009/02/silverlightrelativesourcebinding.zip'>silverlightrelativesourcebinding.zip</a>.</p>
<p>Enjoy, Colin E.</p>

]]></content:encoded>
			<wfw:commentRss>http://www.scottlogic.co.uk/blog/colin/2009/02/relativesource-binding-in-silverlight/feed/</wfw:commentRss>
		<slash:comments>35</slash:comments>
		</item>
		<item>
		<title>ElementName binding in Silverlight via Attached Behaviours</title>
		<link>http://www.scottlogic.co.uk/blog/colin/2009/02/elementname-binding-in-silverlight-via-attached-behaviours/</link>
		<comments>http://www.scottlogic.co.uk/blog/colin/2009/02/elementname-binding-in-silverlight-via-attached-behaviours/#comments</comments>
		<pubDate>Sun, 22 Feb 2009 18:39:02 +0000</pubDate>
		<dc:creator>Colin Eberhardt</dc:creator>
				<category><![CDATA[codeproject]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[attached behaviour]]></category>
		<category><![CDATA[binding]]></category>
		<category><![CDATA[silverlight]]></category>

		<guid isPermaLink="false">http://www.scottlogic.co.uk/blog/colin/?p=127</guid>
		<description><![CDATA[As a relative newcomer to Silverlight I was happily greeted by the warm feeling of familiarity when I started developing. It is surprisingly easy to make the transition from WPF to Silverlight developer, with most of the core concepts being just the same. However, there are some parts of the WPF framework that you start [...]]]></description>
			<content:encoded><![CDATA[
<div class="topsy_widget_data topsy_theme_light-green" style="float: right;margin-left: 0.75em; background: url(data:,%7B%20%22url%22%3A%20%22http%253A%252F%252Fwww.scottlogic.co.uk%252Fblog%252Fcolin%252F2009%252F02%252Felementname-binding-in-silverlight-via-attached-behaviours%252F%22%2C%20%22style%22%3A%20%22big%22%2C%20%22title%22%3A%20%22ElementName%20binding%20in%20Silverlight%20via%20Attached%20Behaviours%20%23%22%20%7D);"></div>
<p>As a relative newcomer to Silverlight I was happily greeted by the warm feeling of familiarity when I started developing. It is surprisingly easy to make the transition from WPF to Silverlight developer, with most of the core concepts being just the same. However, there are some parts of the WPF framework that you start to miss. One of those is ElementName binding. </p>
<p>For those of you not familiar with the concept I will give a very brief overview. When binding the properties of your visual elements within XAML, the source of this binding will be the object associated with the elements DataContext. This works just fine for binding your business objects to the UI that exposes their properties. However, with WPF, binding gives you so much more than just a mechanism for exposing your business data, it also allows you to bind properties between visual elements. This is a powerful concept that allows you to create complex layouts, beyond that which is possible by the framework provided Panels (for some examples of this, see my article on creating a <a href="http://www.codeproject.com/KB/WPF/WpfWinFormsBulletGraphs.aspx">Bullet Graph</a>). In order to enable this, WPF provides ElementName and RelativeSource bindings, giving you a powerful mechanism for locating other elements within your visual tree to bind to. A simple example, where a rectangle&#8217;s Width is bound to a named slider 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;Rectangle</span> <span style="color: #000066;">Width</span>=<span style="color: #ff0000;">&quot;{Binding Path=Value, ElementName=MySlider}&quot;</span> <span style="color: #000066;">Height</span>=<span style="color: #ff0000;">&quot;20&quot;</span> <span style="color: #000066;">Fill</span>=<span style="color: #ff0000;">&quot;Green&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Slider</span> <span style="color: #000066;">x:Name</span>=<span style="color: #ff0000;">&quot;MySlider&quot;</span> <span style="color: #000066;">Value</span>=<span style="color: #ff0000;">&quot;25&quot;</span> <span style="color: #000066;">Minimum</span>=<span style="color: #ff0000;">&quot;0&quot;</span> <span style="color: #000066;">Maximum</span>=<span style="color: #ff0000;">&quot;300&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span></pre></div></div>

<p>Unfortunately Silverlight does not have this capability. </p>
<p>My first thought was to simply point the DataContext of the target element to the source element in order to allow property binding between them. However, much to my surprise, Silverlight dependency properties <a href="http://silverlight.net/forums/p/20783/72428.aspx">do not support property changed notification</a>. </p>
<p>A common solution to this problem is to employ a Relay Object, as described in <a href="http://www.thejoyofcode.com/Workaround_for_missing_ElementName_in_Silverlight_2_0_Binding.aspx">a number of blog posts</a>. An object with a single property, Value, which implement INotifyPropertyChanged is bound to the two visual elements. A simple example is illustrated 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.Resources<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;local:RelayObject</span> <span style="color: #000066;">x:Key</span>=<span style="color: #ff0000;">&quot;Relay&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:RelayObject.Value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;system:Double<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>20<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/system:Double<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/local:RelayObject.Value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/local:RelayObject<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/UserControl.Resources<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;StackPanel</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;Rectangle</span> <span style="color: #000066;">Width</span>=<span style="color: #ff0000;">&quot;{Binding Path=Value, Source={StaticResource Relay}, Mode=TwoWay&quot;</span> <span style="color: #000066;">Height</span>=<span style="color: #ff0000;">&quot;20&quot;</span> <span style="color: #000066;">Fill</span>=<span style="color: #ff0000;">&quot;Green&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Slider</span> <span style="color: #000066;">Value</span>=<span style="color: #ff0000;">&quot;{Binding Path=Value, Source={StaticResource Relay}, Mode=TwoWay}&quot;</span> <span style="color: #000066;">Minimum</span>=<span style="color: #ff0000;">&quot;0&quot;</span> <span style="color: #000066;">Maximum</span>=<span style="color: #ff0000;">&quot;300&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>Here an instance of our RelayObject is bound to both the Rectangle&#8217;s Width and the Slider&#8217;s Value, effectively binding these to properties together. This works just fine, however it does not really feel like the WPF ElementName binding, furthermore, you have to add a new RelayObject instance for each binding. </p>
<p>My solution makes use of the <a href="http://www.codeproject.com/KB/WPF/AttachedBehaviors.aspx">Attached Behaviour</a> pattern which is becoming very popular in WPF and Silverlight. First we define an attached property which uses a type which contains the information we need to create our binding, i.e source and target properties, and the name of the element which we wish to bind to.</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> BindingProperties
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">string</span> SourceProperty <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> <span style="color: #6666cc; font-weight: bold;">string</span> ElementName <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> <span style="color: #6666cc; font-weight: bold;">string</span> TargetProperty <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: #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;">class</span> BindingHelper
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> BindingProperties GetBinding<span style="color: #008000;">&#40;</span>DependencyObject obj<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #008000;">&#40;</span>BindingProperties<span style="color: #008000;">&#41;</span>obj<span style="color: #008000;">.</span><span style="color: #0000FF;">GetValue</span><span style="color: #008000;">&#40;</span>BindingProperty<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> SetBinding<span style="color: #008000;">&#40;</span>DependencyObject obj, BindingProperties value<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        obj<span style="color: #008000;">.</span><span style="color: #0000FF;">SetValue</span><span style="color: #008000;">&#40;</span>BindingProperty, value<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #0600FF; font-weight: bold;">readonly</span> DependencyProperty BindingProperty <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;Binding&quot;</span>, <span style="color: #008000;">typeof</span><span style="color: #008000;">&#40;</span>BindingProperties<span style="color: #008000;">&#41;</span>, <span style="color: #008000;">typeof</span><span style="color: #008000;">&#40;</span>BindingHelper<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>, OnBinding<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
&nbsp;
    <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
    <span style="color: #008080; font-style: italic;">/// property change event handler for SelectAllButtonTemplate</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> OnBinding<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;
        targetElement<span style="color: #008000;">.</span><span style="color: #0000FF;">Loaded</span> <span style="color: #008000;">+=</span> <span style="color: #008000;">new</span> RoutedEventHandler<span style="color: #008000;">&#40;</span>TargetElement_Loaded<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: #0600FF; font-weight: bold;">static</span> <span style="color: #6666cc; font-weight: bold;">void</span> TargetElement_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>
        FrameworkElement targetElement <span style="color: #008000;">=</span> sender <span style="color: #0600FF; font-weight: bold;">as</span> FrameworkElement<span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">// get the value of our attached property</span>
        BindingProperties bindingProperties <span style="color: #008000;">=</span> GetBinding<span style="color: #008000;">&#40;</span>targetElement<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">// perform our 'ElementName' lookup</span>
        FrameworkElement sourceElement <span style="color: #008000;">=</span> targetElement<span style="color: #008000;">.</span><span style="color: #0000FF;">FindName</span><span style="color: #008000;">&#40;</span>bindingProperties<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>
&nbsp;
        <span style="color: #008080; font-style: italic;">// bind them</span>
        CreateRelayBinding<span style="color: #008000;">&#40;</span>targetElement, sourceElement, bindingProperties<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>What the above code does is it defines the attached property of type BindingProperties. The OnBinding method is invoked whenever this property is attached to a dependency object. Within this event handler, we add a handler to the element&#8217;s Loaded event. This event occurs when the element is laid out within the visual tree and ready for action, it is at this point that we can perform our ElementName lookup.</p>
<p>Within the TargetElement_Loaded event handler we use the <a href="http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.findname(VS.95).aspx">FrameworkElement.FindName</a> to look-up the named source element for our binding. This method locates any element with the given name that is within the same <a href="http://msdn.microsoft.com/en-us/library/cc189026(VS.95).aspx">XAML namescope</a> as itself. Interestingly, this is the same method that Visual Studio uses for creating member variables within your code-behind file from the named elements within your XAML. Once, the named element has been located, a relay binding is constructed between them, 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> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #0600FF; font-weight: bold;">readonly</span> BindingFlags dpFlags <span style="color: #008000;">=</span> BindingFlags<span style="color: #008000;">.</span><span style="color: #0600FF; font-weight: bold;">Public</span> <span style="color: #008000;">|</span> BindingFlags<span style="color: #008000;">.</span><span style="color: #0600FF; font-weight: bold;">Static</span> <span style="color: #008000;">|</span> BindingFlags<span style="color: #008000;">.</span><span style="color: #0000FF;">FlattenHierarchy</span><span style="color: #008000;">;</span>
&nbsp;
<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> CreateRelayBinding<span style="color: #008000;">&#40;</span>FrameworkElement targetElement, FrameworkElement sourceElement,
    <span style="color: #6666cc; font-weight: bold;">string</span> targetProperty, <span style="color: #6666cc; font-weight: bold;">string</span> sourceProperty, IValueConverter converter<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
     <span style="color: #008080; font-style: italic;">// create a relay binding between the two elements</span>
     ValueObject relayObject <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> ValueObject<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;">// find the source dependency property</span>
     FieldInfo<span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> sourceFields <span style="color: #008000;">=</span> sourceElement<span style="color: #008000;">.</span><span style="color: #0000FF;">GetType</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">GetFields</span><span style="color: #008000;">&#40;</span>dpFlags<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
     FieldInfo sourceDependencyPropertyField <span style="color: #008000;">=</span> sourceFields<span style="color: #008000;">.</span><span style="color: #0000FF;">First</span><span style="color: #008000;">&#40;</span>i <span style="color: #008000;">=&gt;</span> i<span style="color: #008000;">.</span><span style="color: #0000FF;">Name</span> <span style="color: #008000;">==</span> sourceProperty <span style="color: #008000;">+</span> <span style="color: #666666;">&quot;Property&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
     DependencyProperty sourceDependencyProperty <span style="color: #008000;">=</span> sourceDependencyPropertyField<span style="color: #008000;">.</span><span style="color: #0000FF;">GetValue</span><span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">&#41;</span> <span style="color: #0600FF; font-weight: bold;">as</span> DependencyProperty<span style="color: #008000;">;</span>
&nbsp;
     <span style="color: #008080; font-style: italic;">// initialise the relay object with the source dependency property value </span>
     relayObject<span style="color: #008000;">.</span><span style="color: #0000FF;">Value</span> <span style="color: #008000;">=</span> sourceElement<span style="color: #008000;">.</span><span style="color: #0000FF;">GetValue</span><span style="color: #008000;">&#40;</span>sourceDependencyProperty<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
     <span style="color: #008080; font-style: italic;">// create the binding for our target element to the relay object, this binding will</span>
     <span style="color: #008080; font-style: italic;">// include the value converter</span>
     Binding targetToRelay <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>
     targetToRelay<span style="color: #008000;">.</span><span style="color: #0000FF;">Source</span> <span style="color: #008000;">=</span> relayObject<span style="color: #008000;">;</span>
     targetToRelay<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;Value&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
     targetToRelay<span style="color: #008000;">.</span><span style="color: #0000FF;">Mode</span> <span style="color: #008000;">=</span> BindingMode<span style="color: #008000;">.</span><span style="color: #0000FF;">TwoWay</span><span style="color: #008000;">;</span>
     targetToRelay<span style="color: #008000;">.</span><span style="color: #0000FF;">Converter</span> <span style="color: #008000;">=</span> converter<span style="color: #008000;">;</span>
&nbsp;
     <span style="color: #008080; font-style: italic;">// find the target dependency property</span>
     FieldInfo<span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> targetFields <span style="color: #008000;">=</span> targetElement<span style="color: #008000;">.</span><span style="color: #0000FF;">GetType</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">GetFields</span><span style="color: #008000;">&#40;</span>dpFlags<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
     FieldInfo targetDependencyPropertyField <span style="color: #008000;">=</span> targetFields<span style="color: #008000;">.</span><span style="color: #0000FF;">First</span><span style="color: #008000;">&#40;</span>i <span style="color: #008000;">=&gt;</span> i<span style="color: #008000;">.</span><span style="color: #0000FF;">Name</span> <span style="color: #008000;">==</span> targetProperty <span style="color: #008000;">+</span> <span style="color: #666666;">&quot;Property&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
     DependencyProperty targetDependencyProperty <span style="color: #008000;">=</span> targetDependencyPropertyField<span style="color: #008000;">.</span><span style="color: #0000FF;">GetValue</span><span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">&#41;</span> <span style="color: #0600FF; font-weight: bold;">as</span> DependencyProperty<span style="color: #008000;">;</span>
&nbsp;
     <span style="color: #008080; font-style: italic;">// set the binding on our target element</span>
     targetElement<span style="color: #008000;">.</span><span style="color: #0000FF;">SetBinding</span><span style="color: #008000;">&#40;</span>targetDependencyProperty, targetToRelay<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
     <span style="color: #008080; font-style: italic;">// create the binding for our source element to the relay object</span>
     Binding sourceToRelay <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>
     sourceToRelay<span style="color: #008000;">.</span><span style="color: #0000FF;">Source</span> <span style="color: #008000;">=</span> relayObject<span style="color: #008000;">;</span>
     sourceToRelay<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;Value&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
     sourceToRelay<span style="color: #008000;">.</span><span style="color: #0000FF;">Mode</span> <span style="color: #008000;">=</span> BindingMode<span style="color: #008000;">.</span><span style="color: #0000FF;">TwoWay</span><span style="color: #008000;">;</span>
&nbsp;
     <span style="color: #008080; font-style: italic;">// set the binding on our source element</span>
     sourceElement<span style="color: #008000;">.</span><span style="color: #0000FF;">SetBinding</span><span style="color: #008000;">&#40;</span>sourceDependencyProperty, sourceToRelay<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>        
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>The above code simply creates our relay object, initialising its value from the sourtce element, then constructs the bindings from relay-to-source and relay-to-target. The only &#8216;tricky&#8217; part of the above code is the use of reflection to locate the static dependency properties of each element.</p>
<p>Using the above attached property (behaviour), an element name binding can be constructed 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;Rectangle</span> <span style="color: #000066;">Height</span>=<span style="color: #ff0000;">&quot;20&quot;</span> <span style="color: #000066;">Fill</span>=<span style="color: #ff0000;">&quot;Green&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;local:BindingHelper.Binding<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;local:BindingProperties</span> <span style="color: #000066;">ElementName</span>=<span style="color: #ff0000;">&quot;Slider&quot;</span> <span style="color: #000066;">SourceProperty</span>=<span style="color: #ff0000;">&quot;Value&quot;</span> <span style="color: #000066;">TargetProperty</span>=<span style="color: #ff0000;">&quot;Width&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:BindingHelper.Binding<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/Rectangle<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<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;Slider&quot;</span> <span style="color: #000066;">Value</span>=<span style="color: #ff0000;">&quot;20&quot;</span> <span style="color: #000066;">Minimum</span>=<span style="color: #ff0000;">&quot;0&quot;</span> <span style="color: #000066;">Maximum</span>=<span style="color: #ff0000;">&quot;300&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span></pre></div></div>

<p>The advantages of this approach are twofold, firstly, we do not have to explicitly create a relay object for each ElementName bindings, secondly, the source property value is used to initialise the relay object directly. It is also straightforward exercise to extend the above to add ValueConverters into the binding. </p>
<p>But what if we want to bind two different properties to our slider? If for example we want to bind the Widths of two rectangles, we would need to ensure that a single relay object is constructed which is shared by the Slider and both Rectangles. A simple solution to this problem is to maintain a dictionary of the source bindings to their associated relay objects. If we bind more than one target property to a particular source property, the relay object is re-used. Any value converters are specified on the target binding, therefore we can bind multiple properties to the source with different converters.</p>
<p>The following example shows a couple of Rectangles bound to our slider where their Widths are scaled by different factors:</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;Rectangle</span> <span style="color: #000066;">Height</span>=<span style="color: #ff0000;">&quot;20&quot;</span> <span style="color: #000066;">Fill</span>=<span style="color: #ff0000;">&quot;Green&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;local:BindingHelper.Binding<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;local:BindingProperties</span> <span style="color: #000066;">ElementName</span>=<span style="color: #ff0000;">&quot;Slider&quot;</span> <span style="color: #000066;">SourceProperty</span>=<span style="color: #ff0000;">&quot;Value&quot;</span></span>
<span style="color: #009900;">            <span style="color: #000066;">TargetProperty</span>=<span style="color: #ff0000;">&quot;Width&quot;</span> <span style="color: #000066;">Converter</span>=<span style="color: #ff0000;">&quot;{StaticResource ScalingConverter}&quot;</span> <span style="color: #000066;">ConverterParameter</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:BindingHelper.Binding<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/Rectangle<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Rectangle</span> <span style="color: #000066;">Height</span>=<span style="color: #ff0000;">&quot;20&quot;</span> <span style="color: #000066;">Fill</span>=<span style="color: #ff0000;">&quot;Green&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;local:BindingHelper.Binding<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;local:BindingProperties</span> <span style="color: #000066;">ElementName</span>=<span style="color: #ff0000;">&quot;Slider&quot;</span> <span style="color: #000066;">SourceProperty</span>=<span style="color: #ff0000;">&quot;Value&quot;</span></span>
<span style="color: #009900;">            <span style="color: #000066;">TargetProperty</span>=<span style="color: #ff0000;">&quot;Width&quot;</span> <span style="color: #000066;">Converter</span>=<span style="color: #ff0000;">&quot;{StaticResource ScalingConverter}&quot;</span> <span style="color: #000066;">ConverterParameter</span>=<span style="color: #ff0000;">&quot;4&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:BindingHelper.Binding<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/Rectangle<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<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;Slider&quot;</span> <span style="color: #000066;">Value</span>=<span style="color: #ff0000;">&quot;20&quot;</span> <span style="color: #000066;">Minimum</span>=<span style="color: #ff0000;">&quot;0&quot;</span> <span style="color: #000066;">Maximum</span>=<span style="color: #ff0000;">&quot;300&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span></pre></div></div>

<p>And here is a demonstration of the above implemented both manually with relay objects and with this attached behaviour:</p>
<div id="slPluginHost"> <object id="SilverlightPlugin" width="400" 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/02/silverlightbinding.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>For details of the above, please refer to the attached <a href='http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2009/02/silverlightelementnamebinding.zip'>project download</a>.</p>
<p>This approch does have a few downsides &#8211; unfortunately the syntax is a little verbose. Also, in its present form you can only create on element name binding per visual element. However, the interesting feature of this technique is that it could be readily adapted to search for the source element in other ways, for example emulating the WPF relative source bindings. Perhaps I will have a go at that one next week &#8230;.</p>
<p>You can download the <a href='http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2009/02/silverlightelementnamebinding.zip'>sourcecode</a> for this blog post.</p>

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

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

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

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

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

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

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

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

]]></content:encoded>
			<wfw:commentRss>http://www.scottlogic.co.uk/blog/colin/2009/02/styling-hard-to-reach-elements-in-control-templates-with-attached-behaviours/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>Adding a Location Crosshair to Silverlight Charts</title>
		<link>http://www.scottlogic.co.uk/blog/colin/2009/02/adding-a-location-crosshair-to-silverlight-charts/</link>
		<comments>http://www.scottlogic.co.uk/blog/colin/2009/02/adding-a-location-crosshair-to-silverlight-charts/#comments</comments>
		<pubDate>Wed, 04 Feb 2009 14:33:32 +0000</pubDate>
		<dc:creator>Colin Eberhardt</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[charts]]></category>
		<category><![CDATA[silverlight]]></category>

		<guid isPermaLink="false">http://www.scottlogic.co.uk/blog/colin/?p=99</guid>
		<description><![CDATA[UPDATE &#8211; The March09 update of the Silverlight toolkit is incompatible with the code detailed below. For an up-to-date version see the following blog post. This blog post describes how to add a location crosshair to your Silverlight charts as shown below: The chart itself is rendered using the charting component of the recently release [...]]]></description>
			<content:encoded><![CDATA[
<div class="topsy_widget_data topsy_theme_light-green" style="float: right;margin-left: 0.75em; background: url(data:,%7B%20%22url%22%3A%20%22http%253A%252F%252Fwww.scottlogic.co.uk%252Fblog%252Fcolin%252F2009%252F02%252Fadding-a-location-crosshair-to-silverlight-charts%252F%22%2C%20%22style%22%3A%20%22big%22%2C%20%22title%22%3A%20%22Adding%20a%20Location%20Crosshair%20to%20Silverlight%20Charts%20%23%22%20%7D);"></div>
<div style="background-color:#fdd; margin:5px; padding:5px; border: solid 2px red;"><b>UPDATE</b> &#8211; The March09 update of the Silverlight toolkit is incompatible with the code detailed below. For an up-to-date version see the <a href="http://www.scottlogic.co.uk/blog/colin/2009/03/adding-a-location-crosshair-to-silverlight-charts-again/">following blog post</a>.</div>
<p>This blog post describes how to add a location crosshair to your Silverlight charts as shown below:</p>
<div id="slPluginHost"> <object id="SilverlightPlugin" width="400" height="300" data="data:application/x-silverlight," type="application/x-silverlight-2" ><param name="source" value="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2009/02/sllinechartcrosshair1.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 chart itself is rendered using the charting component of the recently release <a href="http://www.codeplex.com/Silverlight">Silverlight Toolkit</a>. Creating and displaying a simple line chart is as simple as referencing the correct silverlight toolkit namespaces and placing a chart with an associated lineseries into the XAML for your page:</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;charting:Chart</span> <span style="color: #000066;">Name</span>=<span style="color: #ff0000;">&quot;Chart&quot;</span> <span style="color: #000066;">PlotAreaStyle</span>=<span style="color: #ff0000;">&quot;{StaticResource PlotAreaStyle}&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;charting:LineSeries</span></span>
<span style="color: #009900;">		<span style="color: #000066;">IndependentValueBinding</span>=<span style="color: #ff0000;">&quot;{Binding Path=Key}&quot;</span></span>
<span style="color: #009900;">		<span style="color: #000066;">DependentValueBinding</span>=<span style="color: #ff0000;">&quot;{Binding Path=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;/charting:Chart<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>In this example, the data is provided in the form of an XML file as shown in the snippet 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;?xml</span> <span style="color: #000066;">version</span>=<span style="color: #ff0000;">&quot;1.0&quot;</span> <span style="color: #000066;">encoding</span>=<span style="color: #ff0000;">&quot;UTF-8&quot;</span><span style="color: #000000; font-weight: bold;">?&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;history</span> <span style="color: #000066;">generated</span>=<span style="color: #ff0000;">&quot;2009/02/03 10:51:02 GMT+0000&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;dataPoints<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;dataPoint</span> <span style="color: #000066;">date</span>=<span style="color: #ff0000;">&quot;2009/02/03 08:01:00 GMT+0000&quot;</span> <span style="color: #000066;">change</span>=<span style="color: #ff0000;">&quot;21.61&quot;</span> <span style="color: #000066;">changePercent</span>=<span style="color: #ff0000;">&quot;0.36&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;6073.99&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;dataPoint</span> <span style="color: #000066;">date</span>=<span style="color: #ff0000;">&quot;2009/02/03 08:02:45 GMT+0000&quot;</span> <span style="color: #000066;">change</span>=<span style="color: #ff0000;">&quot;16.11&quot;</span> <span style="color: #000066;">changePercent</span>=<span style="color: #ff0000;">&quot;0.27&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;6068.49&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    ...
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;dataPoint</span> <span style="color: #000066;">date</span>=<span style="color: #ff0000;">&quot;2009/02/03 10:50:45 GMT+0000&quot;</span> <span style="color: #000066;">change</span>=<span style="color: #ff0000;">&quot;0.4&quot;</span> <span style="color: #000066;">changePercent</span>=<span style="color: #ff0000;">&quot;0.01&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;6052.78&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/dataPoints<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/history<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>This data shows the performance of the FTSE 100 index on a relatively uneventful morning. The XML file is read using LINQ to XML into a collection of KeyValuePairs. The LineSeries&#8217; ItemsSource is set to the result of this query, with the bindings in the above XAML binding the Key and Value properties of each KeyValuePair instance.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">protected</span> LineSeries LineSeries
<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: #008000;">&#40;</span>LineSeries<span style="color: #008000;">&#41;</span>Chart<span style="color: #008000;">.</span><span style="color: #0000FF;">Series</span><span style="color: #008000;">&#91;</span><span style="color: #FF0000;">0</span><span style="color: #008000;">&#93;</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> 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;
    XDocument doc <span style="color: #008000;">=</span> XDocument<span style="color: #008000;">.</span><span style="color: #0000FF;">Load</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;chartData.xml&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    var elements <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">from</span> dataPoint <span style="color: #0600FF; font-weight: bold;">in</span> doc<span style="color: #008000;">.</span><span style="color: #0000FF;">Descendants</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;dataPoint&quot;</span><span style="color: #008000;">&#41;</span>                           
                   <span style="color: #0600FF; font-weight: bold;">select</span> <span style="color: #008000;">new</span> KeyValuePair<span style="color: #008000;">&lt;</span>DateTime, <span style="color: #6666cc; font-weight: bold;">double</span><span style="color: #008000;">&gt;</span>
                   <span style="color: #008000;">&#40;</span>
                       DateTime<span style="color: #008000;">.</span><span style="color: #0000FF;">Parse</span><span style="color: #008000;">&#40;</span>dataPoint<span style="color: #008000;">.</span><span style="color: #0000FF;">Attribute</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;date&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Value</span><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;">19</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>,
                       <span style="color: #6666cc; font-weight: bold;">Double</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Parse</span><span style="color: #008000;">&#40;</span>dataPoint<span style="color: #008000;">.</span><span style="color: #0000FF;">Attribute</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;value&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Value</span><span style="color: #008000;">&#41;</span>
                   <span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    LineSeries<span style="color: #008000;">.</span><span style="color: #0000FF;">ItemsSource</span> <span style="color: #008000;">=</span> elements<span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>This results in the following (rather ugly!) chart:</p>
<p><a href="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2009/02/ftse100.png"><img class="alignnone size-full wp-image-107" title="ftse100" src="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2009/02/ftse100.png" alt="ftse100" width="400" height="167" /></a></p>
<p>Whilst the background fade effect and line series datapoints can be modified by styling the chart, the removal of unwanted elements such as the legend require us to delve into the the Chart&#8217;s control template. The modified control template 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;charting:Chart.Template<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ControlTemplate</span> <span style="color: #000066;">TargetType</span>=<span style="color: #ff0000;">&quot;charting:Chart&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Grid</span> <span style="color: #000066;">Name</span>=<span style="color: #ff0000;">&quot;ChartArea&quot;</span> <span style="color: #000066;">Style</span>=<span style="color: #ff0000;">&quot;{TemplateBinding ChartAreaStyle}&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
&nbsp;
            <span style="color: #808080; font-style: italic;">&lt;!-- NOTE: the chart legend and title have been removed --&gt;</span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Grid</span> <span style="color: #000066;">Height</span>=<span style="color: #ff0000;">&quot;250&quot;</span> <span style="color: #000066;">x:Name</span>=<span style="color: #ff0000;">&quot;PlotArea&quot;</span> <span style="color: #000066;">Style</span>=<span style="color: #ff0000;">&quot;{TemplateBinding PlotAreaStyle}&quot;</span></span>
<span style="color: #009900;">                  <span style="color: #000066;">MouseMove</span>=<span style="color: #ff0000;">&quot;PlotArea_MouseMove&quot;</span> <span style="color: #000066;">MouseEnter</span>=<span style="color: #ff0000;">&quot;PlotArea_MouseEnter&quot;</span> <span style="color: #000066;">MouseLeave</span>=<span style="color: #ff0000;">&quot;PlotArea_MouseLeave&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
&nbsp;
                <span style="color: #808080; font-style: italic;">&lt;!-- the standard chart template components --&gt;</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;GridLinesContainer&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Grid</span> <span style="color: #000066;">x:Name</span>=<span style="color: #ff0000;">&quot;SeriesContainer&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;#FF919191&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>
&nbsp;
                <span style="color: #808080; font-style: italic;">&lt;!-- a location crosshair --&gt;</span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Grid</span> <span style="color: #000066;">Name</span>=<span style="color: #ff0000;">&quot;Crosshair&quot;</span> <span style="color: #000066;">Visibility</span>=<span style="color: #ff0000;">&quot;Collapsed&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;">Name</span>=<span style="color: #ff0000;">&quot;Vertical&quot;</span> <span style="color: #000066;">X1</span>=<span style="color: #ff0000;">&quot;{Binding Path=X}&quot;</span> <span style="color: #000066;">Y1</span>=<span style="color: #ff0000;">&quot;0&quot;</span> <span style="color: #000066;">X2</span>=<span style="color: #ff0000;">&quot;{Binding Path=X}&quot;</span> <span style="color: #000066;">Y2</span>=<span style="color: #ff0000;">&quot;250&quot;</span> <span style="color: #000066;">Stroke</span>=<span style="color: #ff0000;">&quot;Black&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;">Name</span>=<span style="color: #ff0000;">&quot;Horizontal&quot;</span> <span style="color: #000066;">X1</span>=<span style="color: #ff0000;">&quot;0&quot;</span> <span style="color: #000066;">Y1</span>=<span style="color: #ff0000;">&quot;{Binding Path=Y}&quot;</span> <span style="color: #000066;">X2</span>=<span style="color: #ff0000;">&quot;400&quot;</span> <span style="color: #000066;">Y2</span>=<span style="color: #ff0000;">&quot;{Binding Path=Y}&quot;</span> <span style="color: #000066;">Stroke</span>=<span style="color: #ff0000;">&quot;Black&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>
&nbsp;
                <span style="color: #808080; font-style: italic;">&lt;!-- a location 'legend' --&gt;</span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Border</span> <span style="color: #000066;">Name</span>=<span style="color: #ff0000;">&quot;LocationIndicator&quot;</span> <span style="color: #000066;">Visibility</span>=<span style="color: #ff0000;">&quot;Collapsed&quot;</span> <span style="color: #000066;">Style</span>=<span style="color: #ff0000;">&quot;{StaticResource LocationLegendStyle}&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: #000066;">Margin</span>=<span style="color: #ff0000;">&quot;5&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
                        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;TextBlock</span> <span style="color: #000066;">Text</span>=<span style="color: #ff0000;">&quot;Location: &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=Key}&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;, &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=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;/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;/Grid<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;/ControlTemplate<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/charting:Chart.Template<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>In the above template you can see a couple of Grids, one named GridLinesContainer, and the other names SeriesContainer. When constructing the chart, the chart control will navigate the visual tree constructed from its control template to find elements of these names. It will then add the grid lines and series to these containers accordingly. This gives us the freedom to modify the chart&#8217;s control template whilst still allowing it to function normally. In the above template I have added two new elements, a cross hair and a location indicator. I have also added handlers for a few of the mouse events on the plot area.</p>
<p>The mouse move event handler in the code behind finds the current mouse position within the PlotArea grid. Firstly, the coordinates of this point are found within the chart coordinate system (more on this later), following this, the DataContexts for the Crosshair and PlotArea are set to the mouse position and location within the chart coordinate system respectively. Looking in the above XAML we can see that the Crosshair contains a pair of lines which are bound to the X and Y properties of their DataContext, ensuring that the two lines intersect at the current mouse location. The LocationIndicator will inherit the PlotArea&#8217;s DataContext, allowing it to output the current location in the chart coordinate system.</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> PlotArea_MouseMove<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">object</span> sender, MouseEventArgs 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>LineSeries<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;">&#41;</span>
        <span style="color: #0600FF; font-weight: bold;">return</span><span style="color: #008000;">;</span>
&nbsp;
    Point mousePos <span style="color: #008000;">=</span> e<span style="color: #008000;">.</span><span style="color: #0000FF;">GetPosition</span><span style="color: #008000;">&#40;</span>PlotArea<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    KeyValuePair<span style="color: #008000;">&lt;</span>DateTime, <span style="color: #6666cc; font-weight: bold;">double</span><span style="color: #008000;">&gt;</span> crosshairLocation <span style="color: #008000;">=</span> GetPlotAreaCoordinates<span style="color: #008000;">&#40;</span>mousePos<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    PlotArea<span style="color: #008000;">.</span><span style="color: #0000FF;">DataContext</span> <span style="color: #008000;">=</span> crosshairLocation<span style="color: #008000;">;</span>
    Crosshair<span style="color: #008000;">.</span><span style="color: #0000FF;">DataContext</span> <span style="color: #008000;">=</span> mousePos<span style="color: #008000;">;</span>
    PlotArea<span style="color: #008000;">.</span><span style="color: #0000FF;">Cursor</span> <span style="color: #008000;">=</span> Cursors<span style="color: #008000;">.</span><span style="color: #0000FF;">None</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">protected</span> Grid PlotArea
<span style="color: #008000;">&#123;</span>
    get <span style="color: #008000;">&#123;</span> <span style="color: #0600FF; font-weight: bold;">return</span> ChartArea<span style="color: #008000;">.</span><span style="color: #0000FF;">FindName</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;PlotArea&quot;</span><span style="color: #008000;">&#41;</span> <span style="color: #0600FF; font-weight: bold;">as</span> Grid<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;">protected</span> Grid Crosshair
<span style="color: #008000;">&#123;</span>
    get <span style="color: #008000;">&#123;</span> <span style="color: #0600FF; font-weight: bold;">return</span> ChartArea<span style="color: #008000;">.</span><span style="color: #0000FF;">FindName</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Crosshair&quot;</span><span style="color: #008000;">&#41;</span> <span style="color: #0600FF; font-weight: bold;">as</span> Grid<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;">protected</span> Grid ChartArea
<span style="color: #008000;">&#123;</span>
    get
    <span style="color: #008000;">&#123;</span>
        <span style="color: #008080; font-style: italic;">// chart area is within a different namescope to this page, therefore</span>
        <span style="color: #008080; font-style: italic;">// we must navigate the visual tree to locate it</span>
        <span style="color: #0600FF; font-weight: bold;">return</span> VisualTreeHelper<span style="color: #008000;">.</span><span style="color: #0000FF;">GetChild</span><span style="color: #008000;">&#40;</span>Chart, <span style="color: #FF0000;">0</span><span style="color: #008000;">&#41;</span> <span style="color: #0600FF; font-weight: bold;">as</span> Grid<span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>One thing worth noting in the above code is that way in which the PlotArea and Crosshair elements are located. Usually it is possible to simply name elements within your XAML using their Name attribute then refer to them directly in the code-behind or locate them via the <a href="msdn.microsoft.com/en-us/library/bb979952(VS.95).aspx">DependencyObject.FindName</a> method. However, FindName relies on the named element being in the same namescope. Control template are in a different namescope to the XAML page which they are defined within, therefore we have to navigate the visual tree to find the root element of the chart control, then invoke FindName from there. See the MSDN page on <a href="http://msdn.microsoft.com/en-us/library/cc189026(VS.95).aspx#NamescopesinTemplates">XAML namescopes</a> for more details.</p>
<p>The GetPlotAreaCoordinates method is given below:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">private</span> KeyValuePair<span style="color: #008000;">&lt;</span>DateTime, <span style="color: #6666cc; font-weight: bold;">double</span><span style="color: #008000;">&gt;</span> GetPlotAreaCoordinates<span style="color: #008000;">&#40;</span>Point position<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    Range<span style="color: #008000;">&lt;</span>IComparable<span style="color: #008000;">&gt;</span> yAxisHit <span style="color: #008000;">=</span> <span style="color: #008000;">&#40;</span><span style="color: #008000;">&#40;</span>IRangeAxis<span style="color: #008000;">&#41;</span>YAxis<span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">GetPlotAreaCoordinateValueRange</span><span style="color: #008000;">&#40;</span>PlotArea<span style="color: #008000;">.</span><span style="color: #0000FF;">Height</span> <span style="color: #008000;">-</span> position<span style="color: #008000;">.</span><span style="color: #0000FF;">Y</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    Range<span style="color: #008000;">&lt;</span>IComparable<span style="color: #008000;">&gt;</span> xAxisHit <span style="color: #008000;">=</span> <span style="color: #008000;">&#40;</span><span style="color: #008000;">&#40;</span>IRangeAxis<span style="color: #008000;">&#41;</span>XAxis<span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">GetPlotAreaCoordinateValueRange</span><span style="color: #008000;">&#40;</span>position<span style="color: #008000;">.</span><span style="color: #0000FF;">X</span><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> KeyValuePair<span style="color: #008000;">&lt;</span>DateTime, <span style="color: #6666cc; font-weight: bold;">double</span><span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#40;</span>DateTime<span style="color: #008000;">&#41;</span>xAxisHit<span style="color: #008000;">.</span><span style="color: #0000FF;">Minimum</span>, <span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">double</span><span style="color: #008000;">&#41;</span>yAxisHit<span style="color: #008000;">.</span><span style="color: #0000FF;">Minimum</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>The silverlight chart axes actually provides methods which can be used to translate from screen coordinates to chart coordinates via the IRangeAxis interface, however they are hidden by <a href="http://msdn.microsoft.com/en-us/library/aa288461(VS.71).aspx">explicit interface implementation</a> of these interface methods by the concrete axis classes. It is a shame that such useful methods are hidden! I have never really seen the value of explicit interface implementation.</p>
<p>In conclusion, this blog post has shown how simple it is to add a crosshair to your silverlight linecharts. What I personally find interesting is the way in which you can not only customise the appearance of Silverlight (and WPF) controls, but also add behaviour without the need to subclass the controls themselves. I think that this makes life easier for the users of Silverlight/WPF controls, in that they can use the same techniques to extend any control rather than relying on the control having built in extension points (it is often a source of frustration when developing with Windows Forms (or similar technologies) when you wish to customise some aspect of an existing control, however the control author has not provided events, or virtual methods for this purpose). It also of course makes life easier for the control developer in that they do not have to spend so much time thinking about how their control might be extended and adapted by its users. </p>
<p>You can download a visual studio project with the code from this blog post, <a href='http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2009/02/sllinechartcrosshair.zip'>sllinechartcrosshair.zip</a>.</p>
<p>Regards, Colin E.</p>

]]></content:encoded>
			<wfw:commentRss>http://www.scottlogic.co.uk/blog/colin/2009/02/adding-a-location-crosshair-to-silverlight-charts/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>BindingGroups for Total View Validation</title>
		<link>http://www.scottlogic.co.uk/blog/colin/2009/01/bindinggroups-for-total-view-validation/</link>
		<comments>http://www.scottlogic.co.uk/blog/colin/2009/01/bindinggroups-for-total-view-validation/#comments</comments>
		<pubDate>Mon, 26 Jan 2009 14:27:40 +0000</pubDate>
		<dc:creator>Colin Eberhardt</dc:creator>
				<category><![CDATA[codeproject]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[validation]]></category>

		<guid isPermaLink="false">http://www.scottlogic.co.uk/blog/colin/?p=91</guid>
		<description><![CDATA[Over the weekend Sacha published a new article on codeproject, Total View Validation (does Sacha ever sleep?). This article addresses some of the perceived problems with the WPF binding framework, firstly, that the standard solution of using the ValidatesOnDataErrors property forces you to place validation logic into your bound business objects, and secondly, that there [...]]]></description>
			<content:encoded><![CDATA[
<div class="topsy_widget_data topsy_theme_light-green" style="float: right;margin-left: 0.75em; background: url(data:,%7B%20%22url%22%3A%20%22http%253A%252F%252Fwww.scottlogic.co.uk%252Fblog%252Fcolin%252F2009%252F01%252Fbindinggroups-for-total-view-validation%252F%22%2C%20%22style%22%3A%20%22big%22%2C%20%22title%22%3A%20%22BindingGroups%20for%20Total%20View%20Validation%20%23%22%20%7D);"></div>
<p>Over the weekend Sacha published a new article on codeproject, <a href="http://www.codeproject.com/KB/WPF/GlobalWPFValidation.aspx">Total View Validation</a> (does Sacha ever sleep?).  This article addresses some of the perceived problems with the WPF binding framework, firstly, that the standard solution of using the <a href="http://msdn.microsoft.com/en-us/library/system.windows.data.binding.validatesondataerrors.aspx">ValidatesOnDataErrors</a> property forces you to place validation logic into your bound business objects, and secondly, that there is no way to perform validation across multiple objects. His solution to both these problems was to construct a view model which contains the validation rules and applies them to all the objects within the form. A collection of validation failures are associated with the view model. These can either be rendered in their entirety or each control within the view can render errors relating to their context.</p>
<p>This blog post describes how BindingGroups can be used to address the problem of applying validation rules to multiple objects.</p>
<p>BindingGroups were introduced as part of .NET 3.5 SP1, Vincent Sibal provides a good introduction to this new features <a href="http://blogs.msdn.com/vinsibal/archive/2008/08/11/wpf-3-5-sp1-feature-bindinggroups-with-item-level-validation.aspx">on his blog</a>. I have previously blogged on the subject of BindingGroups, where I demonstrated how they can be used to provide <a href="http://www.scottlogic.co.uk/blog/colin/2008/11/using-bindinggroups-for-greater-control-over-input-validation/"> improved error messages when type conversion fails during the binding process</a>.</p>
<p>In this post I will take the application from Sacha&#8217;s article and modify it to use BindingGroups. The following is a screenshot of the application:</p>
<p><img class="alignnone size-full wp-image-93" title="form" src="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2009/01/form.png" alt="form" width="302" height="415" /></p>
<p>The form displays the details of two People (two instances of the Person class). The user inputs data using the above controls then clicks the Validate button to run all the Form&#8217;s validation rules. Most of the validation rules relate to a single property of the bound object, e.g. FullName cannot be empty. However there is one trick validation rule:</p>
<p><strong>&#8220;If Person 1&#8242;s age is less than 18, Person 2&#8242;s age cannot be zero&#8221;</strong></p>
<p>This rule cannot be evaluated by assocaiting it with the Age property of either person. It requires access to both Person instances, hence it really belongs at the scope of the form itself. This is where BindingGroups come in &#8230;</p>
<p>The XAML below shows our form which consists of a pair of StackPanels that contain fields bound to our Person instances by setting their DataContext properties in the code-behind. The &#8216;root&#8217; element of the Window contains our BindingGroup.</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;">Name</span>=<span style="color: #ff0000;">&quot;RootElement&quot;</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>
    <span style="color: #808080; font-style: italic;">&lt;!-- the binding group for this form --&gt;</span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;StackPanel.BindingGroup<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;BindingGroup</span> <span style="color: #000066;">Name</span>=<span style="color: #ff0000;">&quot;FormBindingGroup&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;BindingGroup.ValidationRules<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;local:PersonValidationRule</span></span>
<span style="color: #009900;">                            <span style="color: #000066;">ValidationStep</span>=<span style="color: #ff0000;">&quot;CommittedValue&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/BindingGroup.ValidationRules<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/BindingGroup<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/StackPanel.BindingGroup<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> <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: #808080; font-style: italic;">&lt;!-- Person One fields --&gt;</span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;StackPanel</span> <span style="color: #000066;">Name</span>=<span style="color: #ff0000;">&quot;personOnePanel&quot;</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>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Label</span> <span style="color: #000066;">Content</span>=<span style="color: #ff0000;">&quot;Person1&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
                <span style="color: #808080; font-style: italic;">&lt;!-- FirstName Property--&gt;</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;Label</span> <span style="color: #000066;">Content</span>=<span style="color: #ff0000;">&quot;FirstName&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=FirstName, </span>
<span style="color: #009900;">                                           BindingGroupName=FormBindingGroup,</span>
<span style="color: #009900;">                                           ValidatesOnDataErrors=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;/StackPanel<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
                <span style="color: #808080; font-style: italic;">&lt;!-- LastName Property--&gt;</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>
&nbsp;
            <span style="color: #808080; font-style: italic;">&lt;!-- Person Twofields --&gt;</span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;StackPanel</span> <span style="color: #000066;">Name</span>=<span style="color: #ff0000;">&quot;personTwoPanel&quot;</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>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Label</span> <span style="color: #000066;">Content</span>=<span style="color: #ff0000;">&quot;Person2&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
                <span style="color: #808080; font-style: italic;">&lt;!-- FirstName Property--&gt;</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;Label</span> <span style="color: #000066;">Content</span>=<span style="color: #ff0000;">&quot;FirstName&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=FirstName, </span>
<span style="color: #009900;">                                           BindingGroupName=FormBindingGroup,</span>
<span style="color: #009900;">                                           ValidatesOnDataErrors=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;/StackPanel<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
                <span style="color: #808080; font-style: italic;">&lt;!-- LastName Property--&gt;</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>
&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>
&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> <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;Button</span> <span style="color: #000066;">x:Name</span>=<span style="color: #ff0000;">&quot;btnValidate&quot;</span> <span style="color: #000066;">Content</span>=<span style="color: #ff0000;">&quot;Validate&quot;</span> <span style="color: #000066;">Margin</span>=<span style="color: #ff0000;">&quot;5&quot;</span>  <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&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>
<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>Rules associated with a BindingGroup have access to both their associated binding expressions, and the source objects used by these bindings. A BindingGroup becomes associated with a collection of binding expressions if it shares the same DataContext. However, in the above example we have a pair of objects, therefore we cannot share a DataContext across all the elements in our XAML (this is not strictly true, we could construct a view model for this purpose, however I really want to illustrate one of the other features of BindingGroups). BindingGroups can also be explicitly associated with a Binding via its BindingGroupName property.</p>
<p>So just what exactly can we do with our BindingGroup? It is possible to execute this rule at various different steps of the binding process, for example, it is possible to evaluate the rule before type conversion has occurred. In this instance, we are only interested in the converted value, hence the ValidationStep property is set to CommittedValue. The rule itself is very simple:</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> PersonValidationRule <span style="color: #008000;">:</span> ValidationRule
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">override</span> ValidationResult Validate<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">object</span> value, CultureInfo cultureInfo<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        BindingGroup bindingGroup <span style="color: #008000;">=</span> <span style="color: #008000;">&#40;</span>BindingGroup<span style="color: #008000;">&#41;</span>value<span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">// extract the two bound Person instances.</span>
        Person personOne <span style="color: #008000;">=</span> bindingGroup<span style="color: #008000;">.</span><span style="color: #0000FF;">Items</span><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> Person<span style="color: #008000;">;</span>
        Person personTwo <span style="color: #008000;">=</span> bindingGroup<span style="color: #008000;">.</span><span style="color: #0000FF;">Items</span><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> Person<span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>personTwo<span style="color: #008000;">.</span><span style="color: #0000FF;">Age</span><span style="color: #008000;">==</span><span style="color: #FF0000;">0</span> <span style="color: #008000;">&amp;&amp;</span> personOne<span style="color: #008000;">.</span><span style="color: #0000FF;">Age</span><span style="color: #008000;">&lt;</span><span style="color: #FF0000;">18</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> ValidationResult<span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">false</span>,
                     <span style="color: #666666;">&quot;Person 2 Age can't be zero if Person1 Age &lt; 18&quot;</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;">return</span> ValidationResult<span style="color: #008000;">.</span><span style="color: #0000FF;">ValidResult</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>We simply retrieve both Person instances, apply our rule raising an error if our condition is not met. Any validation errors returned by the BindingGroup become associated with the <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.validation.errors.aspx">Validation.Errors</a> attached property of the element which the BindingGroup is associated with. Therefore they can be accessed and styled in the &#8216;standard&#8217; way, for example:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Style</span> <span style="color: #000066;">TargetType</span>=<span style="color: #ff0000;">&quot;{x:Type TextBox}&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Style.Triggers<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Trigger</span> <span style="color: #000066;">Property</span>=<span style="color: #ff0000;">&quot;Validation.HasError&quot;</span> <span style="color: #000066;">Value</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;Setter</span> <span style="color: #000066;">Property</span>=<span style="color: #ff0000;">&quot;ToolTip&quot;</span></span>
<span style="color: #009900;">                <span style="color: #000066;">Value</span>=<span style="color: #ff0000;">&quot;{Binding RelativeSource={RelativeSource Self}, </span>
<span style="color: #009900;">                       Path=(Validation.Errors)[0].ErrorContent}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/Trigger<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/Style.Triggers<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/Style<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>See the excellent article <a href="http://www.codeproject.com/KB/WPF/wpfvalidation.aspx">Validation in WPF</a> for details. </p>
<p>However, BindingGroups offer one further advantage, validation errors from the associated binding expressions are also placed in the Validation.Errors collection, therefore we can output all the validation errors for our form by binding to this property 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;ItemsControl</span> <span style="color: #000066;">ItemsSource</span>=<span style="color: #ff0000;">&quot;{Binding Path=(Validation.Errors), ElementName=RootElement}&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;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;Label</span> <span style="color: #000066;">Foreground</span>=<span style="color: #ff0000;">&quot;Red&quot;</span> <span style="color: #000066;">Content</span>=<span style="color: #ff0000;">&quot;{Binding Path=ErrorContent}&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 following screenshot shows the form where multiple validation errors are present:</p>
<p><img src="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2009/01/errors.png" alt="errors" title="errors" width="292" height="484" class="alignnone size-full wp-image-95" /></p>
<p><b>Conclusions</b></p>
<p>So &#8230; which approach is better? BindingGroups or Sacha&#8217;s ViewModel technique?</p>
<p>Personally, I don&#8217;t think there is one best approach &#8211; and this blog post is certainly not an attack on Sacha&#8217;s article, which presents an elegant solution. My intention is to simply show that it is possible to perform validation on multiple objects at a &#8216;wider&#8217; scope with the standard WPF framework. </p>
<p>To quote Mike Hillberg, the <a href="http://blogs.msdn.com/mikehillberg/archive/2008/05/21/Model-see_2C00_-model-do.aspx">Poo is Optional</a>.</p>
<p>A sample project with the code from this post is available for download: <a href="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2009/01/bindinggroupsglobalvalidation.zip">bindinggroupsglobalvalidation.zip</a>.</p>
<p>Regards, Colin E.</p>

]]></content:encoded>
			<wfw:commentRss>http://www.scottlogic.co.uk/blog/colin/2009/01/bindinggroups-for-total-view-validation/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>WPF DataGrid &#8211; Committing changes cell-by-cell</title>
		<link>http://www.scottlogic.co.uk/blog/colin/2009/01/wpf-datagrid-committing-changes-cell-by-cell/</link>
		<comments>http://www.scottlogic.co.uk/blog/colin/2009/01/wpf-datagrid-committing-changes-cell-by-cell/#comments</comments>
		<pubDate>Wed, 21 Jan 2009 17:06:28 +0000</pubDate>
		<dc:creator>Colin Eberhardt</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[DataGrid]]></category>
		<category><![CDATA[IEditableObject]]></category>

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

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

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

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

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

]]></content:encoded>
			<wfw:commentRss>http://www.scottlogic.co.uk/blog/colin/2009/01/wpf-datagrid-committing-changes-cell-by-cell/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>LayoutTransform vs. RenderTransform &#8211; What&#8217;s the Difference?</title>
		<link>http://www.scottlogic.co.uk/blog/colin/2008/12/layouttransform-vs-rendertransform-whats-the-difference/</link>
		<comments>http://www.scottlogic.co.uk/blog/colin/2008/12/layouttransform-vs-rendertransform-whats-the-difference/#comments</comments>
		<pubDate>Fri, 19 Dec 2008 05:45:42 +0000</pubDate>
		<dc:creator>Colin Eberhardt</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[layout]]></category>

		<guid isPermaLink="false">http://wpfadventures.wordpress.com/?p=46</guid>
		<description><![CDATA[I have answered a few forum posts about the WPF transforms recently, mostly regarding confusion between RenderTransform and LayoutTransform. This brief blog post illustrates the difference between the two. The WPF layout system comprises, of two steps, followed by the rendering of the user interface (UI): Measure Arrange Render In the Measure step, the DesiredSize [...]]]></description>
			<content:encoded><![CDATA[
<div class="topsy_widget_data topsy_theme_light-green" style="float: right;margin-left: 0.75em; background: url(data:,%7B%20%22url%22%3A%20%22http%253A%252F%252Fwww.scottlogic.co.uk%252Fblog%252Fcolin%252F2008%252F12%252Flayouttransform-vs-rendertransform-whats-the-difference%252F%22%2C%20%22style%22%3A%20%22big%22%2C%20%22title%22%3A%20%22LayoutTransform%20vs.%20RenderTransform%20-%20What%27s%20the%20Difference%3F%20%23%22%20%7D);"></div>
<p>I have answered a few forum posts about the WPF transforms recently, mostly regarding confusion between <a href="http://msdn.microsoft.com/en-us/library/system.windows.uielement.rendertransform.aspx">RenderTransform</a> and <a href="http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.layouttransform.aspx">LayoutTransform</a>. This brief blog post illustrates the difference between the two.  The WPF <a href="http://msdn.microsoft.com/en-us/library/ms745058.aspx">layout system</a> comprises, of two steps, followed by the rendering of the user interface (UI):</p>
<ul>
<li>Measure</li>
<li>Arrange</li>
<li>Render</li>
</ul>
<p>In the Measure step, the DesiredSize of each element is computed; in the Arrange step the position of child elements within their parents is determined; finally, in the Render step, the result user interface is rendered to the screen.  Layout transforms and Render transforms are computed at different stages of the layout/render process:</p>
<ul>
<li><strong>LayoutTransform</strong></li>
<li>Measure</li>
<li>Arrange</li>
<li><strong>RenderTransform</strong></li>
<li>Render</li>
</ul>
<p>As a result, any transformations associated with an elements LayoutTransform property will have an impact on the subsequent Measure and Arrange steps. Whereas a RenderTransform will not have any impact on the layout process and will only effect rendering.  The difference is probably best illustrated by an example:</p>
<p><a href="http://wpfadventures.files.wordpress.com/2008/12/transforms.png"></a><a href="http://wpfadventures.files.wordpress.com/2008/12/transforms1.png"><img class="alignnone size-full wp-image-49" title="transforms" src="http://wpfadventures.files.wordpress.com/2008/12/transforms1.png" alt="transforms" width="440" height="350" /></a></p>
<p>In the above examples, it can be seen that when a LayoutTransform is applied, neighbouring elements are re-positioned to accommodate the transformed elements, whereas with the RenderTransform they are not. One common use of WPF transforms is to rotate ListView column headings. With the above examples it should be obvious that a LayoutTransform is required to achieve this effect.</p>
<p>You can download the demo project, <a href="http://wpfadventures.files.wordpress.com/2008/12/wpfrenderandlayouttransforms.doc">wpfrenderandlayouttransforms</a>, changing the file extension from .doc to .zip.</p>
<p>Regards, Colin E.</p>

]]></content:encoded>
			<wfw:commentRss>http://www.scottlogic.co.uk/blog/colin/2008/12/layouttransform-vs-rendertransform-whats-the-difference/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

