<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Thomas Levesque&#039;s .NET blog</title>
	<atom:link href="http://tomlev2.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://tomlev2.wordpress.com</link>
	<description>Tips, tricks and thougts about .NET development</description>
	<lastBuildDate>Mon, 30 Jan 2012 14:57:43 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='tomlev2.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://0.gravatar.com/blavatar/64cdc2d939ad0d3b7c6c0cc4bb4bc712?s=96&#038;d=http%3A%2F%2Fs2.wp.com%2Fi%2Fbuttonw-com.png</url>
		<title>Thomas Levesque&#039;s .NET blog</title>
		<link>http://tomlev2.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://tomlev2.wordpress.com/osd.xml" title="Thomas Levesque&#039;s .NET blog" />
	<atom:link rel='hub' href='http://tomlev2.wordpress.com/?pushpress=hub'/>
		<item>
		<title>[WPF] Using Linq to shape data in a CollectionView</title>
		<link>http://tomlev2.wordpress.com/2011/11/30/wpf-using-linq-to-shape-data-in-a-collectionview/</link>
		<comments>http://tomlev2.wordpress.com/2011/11/30/wpf-using-linq-to-shape-data-in-a-collectionview/#comments</comments>
		<pubDate>Wed, 30 Nov 2011 13:09:45 +0000</pubDate>
		<dc:creator>Thomas Levesque</dc:creator>
				<category><![CDATA[WPF]]></category>
		<category><![CDATA[collectionview]]></category>
		<category><![CDATA[linq]]></category>

		<guid isPermaLink="false">http://tomlev2.wordpress.com/?p=381</guid>
		<description><![CDATA[WPF provides a simple mechanism for shaping collections of data, via the ICollectionView interface and its Filter, SortDescriptions and GroupDescriptions properties: Even though this technique is not difficult to use, it has a few drawbacks: The syntax is a bit clumsy and unnatural: the fact that the filter parameter is an object whereas we now [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tomlev2.wordpress.com&amp;blog=7442815&amp;post=381&amp;subd=tomlev2&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>WPF provides a simple mechanism for shaping collections of data, via the <code>ICollectionView</code> interface and its <code>Filter</code>, <code>SortDescriptions</code> and <code>GroupDescriptions</code> properties:</p>
<p><pre class="brush: csharp;">
// Collection to which the view is bound
public ObservableCollection People { get; private set; }
...

// Default view of the People collection
ICollectionView view = CollectionViewSource.GetDefaultView(People);

// Show only adults
view.Filter = o =&gt; ((Person)o).Age &gt;= 18;

// Sort by last name and first name
view.SortDescriptions.Add(new SortDescription(&quot;LastName&quot;, ListSortDirection.Ascending));
view.SortDescriptions.Add(new SortDescription(&quot;FirstName&quot;, ListSortDirection.Ascending));

// Group by country
view.GroupDescriptions.Add(new PropertyGroupDescription(&quot;Country&quot;));
</pre></p>
<p>Even though this technique is not difficult to use, it has a few drawbacks:</p>
<ul>
<li>The syntax is a bit clumsy and unnatural: the fact that the filter parameter is an <code>object</code> whereas we now it&#8217;s actually of type <code>Person</code> makes the code less readable because of the cast, and the specification of the sort and group descriptions is a little repetitive</li>
<li>Specifying the property names as strings introduces a risk of error, since they&#8217;re not verified by the compiler</li>
</ul>
<p>In the last few years, we got used to use Linq to do this kind of things… it would be nice to be able to do the same for the shaping of an <code>ICollectionView</code>.</p>
<p>Let&#8217;s see what syntax we could use to do it with Linq… something like this perhaps?</p>
<p><pre class="brush: csharp;">
People.Where(p =&gt; p.Age &gt;= 18)
      .OrderBy(p =&gt; p.LastName)
      .ThenBy(p =&gt; p.FirstName)
      .GroupBy(p =&gt; p.Country);
</pre></p>
<p>Or, with the Linq query comprehension syntax:</p>
<p><pre class="brush: csharp;">
from p in People
where p.Age &gt;= 18
orderby p.LastName, p.FirstName
group p by p.Country;
</pre></p>
<p>Obviously, this is not enough: this code only creates a  query on the collection, it doesn&#8217;t modify the <code>CollectionView</code>… but with just a little extra work, we can get the desired result:</p>
<p><pre class="brush: csharp;">
var query =
    from p in People.ShapeView()
    where p.Age &gt;= 18
    orderby p.LastName, p.FirstName
    group p by p.Country;

query.Apply();
</pre></p>
<p>The <code>ShapeView</code> method returns a wrapper which encapsulates the default view of the collection, and exposes <code>Where</code>, <code>OrderBy</code> and <code>GroupBy</code> methods with appropriate signatures to specify the shaping of the <code>CollectionView</code>. Creating the query has no direct effect, the changes are only applied to the view when  <code>Apply</code> is called: that&#8217;s because it&#8217;s better to apply all changes at the same time, using <code>ICollectionView.DeferRefresh</code>, to avoid causing a refresh of the view for each clause of the query. When <code>Apply</code> is called, we can see that the view is correctly updated to reflect the query.</p>
<p>This solution allows to define the filter, sort and grouping in a strongly-typed way, which implies that the code is verified by the compiler. It&#8217;s also more concise and readable than the original code… Just be careful with one thing: some queries that are correct from the compiler&#8217;s point of view won&#8217;t be applicable to a <code>CollectionView</code>. For instance, if you try to group the data by the first letter of the last name (<code>p.LastName.Substring(0, 1)</code>), the <code>GroupBy</code> method will fail because only properties are supported by <code>PropertyGroupDescription</code>.</p>
<p>Note that the wrapper won&#8217;t overwrite the shaping properties of the <code>CollectionView</code> if you don&#8217;t specify the corresponding Linq clause, so you can just modify the current view without specifying everything again. If you need to clear the properties, you can use the <code>ClearFilter</code>, <code>ClearSort</code> and <code>ClearGrouping</code> methods:</p>
<p><pre class="brush: csharp;">
// Remove the grouping and add a sort criteria
People.ShapeView()
      .ClearGrouping()
      .OrderBy(p =&gt; p.LastName);
      .Apply();
</pre></p>
<p>Note that as for a normal Linq query, it&#8217;s possible to use either the query comprehension syntax or to call the methods directly, since the former is just syntactic sugar for the latter.</p>
<p>Finally, here&#8217;s the complete code of the wrapper and the associated extension methods:</p>
<p><pre class="brush: csharp;">
    public static class CollectionViewShaper
    {
        public static CollectionViewShaper&lt;TSource&gt; ShapeView&lt;TSource&gt;(this IEnumerable&lt;TSource&gt; source)
        {
            var view = CollectionViewSource.GetDefaultView(source);
            return new CollectionViewShaper&lt;TSource&gt;(view);
        }

        public static CollectionViewShaper&lt;TSource&gt; Shape&lt;TSource&gt;(this ICollectionView view)
        {
            return new CollectionViewShaper&lt;TSource&gt;(view);
        }
    }

    public class CollectionViewShaper&lt;TSource&gt;
    {
        private readonly ICollectionView _view;
        private Predicate&lt;object&gt; _filter;
        private readonly List&lt;SortDescription&gt; _sortDescriptions = new List&lt;SortDescription&gt;();
        private readonly List&lt;GroupDescription&gt; _groupDescriptions = new List&lt;GroupDescription&gt;();

        public CollectionViewShaper(ICollectionView view)
        {
            if (view == null)
                throw new ArgumentNullException(&quot;view&quot;);
            _view = view;
            _filter = view.Filter;
            _sortDescriptions = view.SortDescriptions.ToList();
            _groupDescriptions = view.GroupDescriptions.ToList();
        }

        public void Apply()
        {
            using (_view.DeferRefresh())
            {
                _view.Filter = _filter;
                _view.SortDescriptions.Clear();
                foreach (var s in _sortDescriptions)
                {
                    _view.SortDescriptions.Add(s);
                }
                _view.GroupDescriptions.Clear();
                foreach (var g in _groupDescriptions)
                {
                    _view.GroupDescriptions.Add(g);
                }
            }
        }
            
        public CollectionViewShaper&lt;TSource&gt; ClearGrouping()
        {
            _groupDescriptions.Clear();
            return this;
        }

        public CollectionViewShaper&lt;TSource&gt; ClearSort()
        {
            _sortDescriptions.Clear();
            return this;
        }

        public CollectionViewShaper&lt;TSource&gt; ClearFilter()
        {
            _filter = null;
            return this;
        }

        public CollectionViewShaper&lt;TSource&gt; ClearAll()
        {
            _filter = null;
            _sortDescriptions.Clear();
            _groupDescriptions.Clear();
            return this;
        }

        public CollectionViewShaper&lt;TSource&gt; Where(Func&lt;TSource, bool&gt; predicate)
        {
            _filter = o =&gt; predicate((TSource)o);
            return this;
        }

        public CollectionViewShaper&lt;TSource&gt; OrderBy&lt;TKey&gt;(Expression&lt;Func&lt;TSource, TKey&gt;&gt; keySelector)
        {
            return OrderBy(keySelector, true, ListSortDirection.Ascending);
        }

        public CollectionViewShaper&lt;TSource&gt; OrderByDescending&lt;TKey&gt;(Expression&lt;Func&lt;TSource, TKey&gt;&gt; keySelector)
        {
            return OrderBy(keySelector, true, ListSortDirection.Descending);
        }

        public CollectionViewShaper&lt;TSource&gt; ThenBy&lt;TKey&gt;(Expression&lt;Func&lt;TSource, TKey&gt;&gt; keySelector)
        {
            return OrderBy(keySelector, false, ListSortDirection.Ascending);
        }

        public CollectionViewShaper&lt;TSource&gt; ThenByDescending&lt;TKey&gt;(Expression&lt;Func&lt;TSource, TKey&gt;&gt; keySelector)
        {
            return OrderBy(keySelector, false, ListSortDirection.Descending);
        }

        private CollectionViewShaper&lt;TSource&gt; OrderBy&lt;TKey&gt;(Expression&lt;Func&lt;TSource, TKey&gt;&gt; keySelector, bool clear, ListSortDirection direction)
        {
            string path = GetPropertyPath(keySelector.Body);
            if (clear)
                _sortDescriptions.Clear();
            _sortDescriptions.Add(new SortDescription(path, direction));
            return this;
        }

        public CollectionViewShaper&lt;TSource&gt; GroupBy&lt;TKey&gt;(Expression&lt;Func&lt;TSource, TKey&gt;&gt; keySelector)
        {
            string path = GetPropertyPath(keySelector.Body);
            _groupDescriptions.Add(new PropertyGroupDescription(path));
            return this;
        }

        private static string GetPropertyPath(Expression expression)
        {
            var names = new Stack&lt;string&gt;();
            var expr = expression;
            while (expr != null &amp;&amp; !(expr is ParameterExpression) &amp;&amp; !(expr is ConstantExpression))
            {
                var memberExpr = expr as MemberExpression;
                if (memberExpr == null)
                    throw new ArgumentException(&quot;The selector body must contain only property or field access expressions&quot;);
                names.Push(memberExpr.Member.Name);
                expr = memberExpr.Expression;
            }
            return String.Join(&quot;.&quot;, names.ToArray());
        }
    }
</pre></p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2ftomlev2.wordpress.com%2f2011%2f11%2f30%2fwpf-using-linq-to-shape-data-in-a-collectionview%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2ftomlev2.wordpress.com%2f2011%2f11%2f30%2fwpf-using-linq-to-shape-data-in-a-collectionview%2f" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tomlev2.wordpress.com/381/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tomlev2.wordpress.com/381/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tomlev2.wordpress.com/381/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tomlev2.wordpress.com/381/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/tomlev2.wordpress.com/381/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/tomlev2.wordpress.com/381/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/tomlev2.wordpress.com/381/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/tomlev2.wordpress.com/381/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tomlev2.wordpress.com/381/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tomlev2.wordpress.com/381/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tomlev2.wordpress.com/381/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tomlev2.wordpress.com/381/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tomlev2.wordpress.com/381/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tomlev2.wordpress.com/381/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tomlev2.wordpress.com&amp;blog=7442815&amp;post=381&amp;subd=tomlev2&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://tomlev2.wordpress.com/2011/11/30/wpf-using-linq-to-shape-data-in-a-collectionview/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f4acdb91aba11ddf8f03d4b12453f3d5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tomlev</media:title>
		</media:content>

		<media:content url="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2ftomlev2.wordpress.com%2f2011%2f11%2f30%2fwpf-using-linq-to-shape-data-in-a-collectionview%2f" medium="image">
			<media:title type="html">kick it on DotNetKicks.com</media:title>
		</media:content>
	</item>
		<item>
		<title>[WPF] Creating parameterized styles with attached properties</title>
		<link>http://tomlev2.wordpress.com/2011/10/01/wpf-creating-parameterized-styles-with-attached-properties/</link>
		<comments>http://tomlev2.wordpress.com/2011/10/01/wpf-creating-parameterized-styles-with-attached-properties/#comments</comments>
		<pubDate>Sat, 01 Oct 2011 00:37:15 +0000</pubDate>
		<dc:creator>Thomas Levesque</dc:creator>
				<category><![CDATA[Tricks]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[attached property]]></category>
		<category><![CDATA[style]]></category>
		<category><![CDATA[template]]></category>

		<guid isPermaLink="false">http://tomlev2.wordpress.com/?p=371</guid>
		<description><![CDATA[Today I&#8217;d like to share a trick that I used quite often in the past few months. Let&#8217;s assume that in order to improve the look of your application, you created custom styles for the standard controls: OK, I&#8217;m not a designer&#8230; but it will serve the purpose well enough to illustrate my point . [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tomlev2.wordpress.com&amp;blog=7442815&amp;post=371&amp;subd=tomlev2&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Today I&#8217;d like to share a trick that I used quite often in the past few months. Let&#8217;s assume that in order to improve the look of your application, you created custom styles for the standard controls:</p>
<p><a href="http://tomlev.files.wordpress.com/2011/09/parameterized_styles11.png"><img src="http://tomlev.files.wordpress.com/2011/09/parameterized_styles11.png?w=780" alt="" title=""   class="aligncenter size-full wp-image-468" /></a></p>
<p>OK, I&#8217;m not a designer&#8230; but it will serve the purpose well enough to illustrate my point <img src='http://s1.wp.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> . These styles are very simple, they&#8217;re just the default styles of <code>CheckBox</code> and <code>RadioButton</code> in which I only changed the templates to replace the <code>BulletChrome</code>s with these awesome blue tick marks. Here&#8217;s the code:</p>
<p><pre class="brush: xml;">
        &lt;Style x:Key=&quot;{x:Type CheckBox}&quot; TargetType=&quot;{x:Type CheckBox}&quot;&gt;
            &lt;Setter Property=&quot;Foreground&quot; Value=&quot;{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}&quot;/&gt;
            &lt;Setter Property=&quot;Background&quot; Value=&quot;{StaticResource CheckBoxFillNormal}&quot;/&gt;
            &lt;Setter Property=&quot;BorderBrush&quot; Value=&quot;{StaticResource CheckBoxStroke}&quot;/&gt;
            &lt;Setter Property=&quot;BorderThickness&quot; Value=&quot;1&quot;/&gt;
            &lt;Setter Property=&quot;FocusVisualStyle&quot; Value=&quot;{StaticResource EmptyCheckBoxFocusVisual}&quot;/&gt;
            &lt;Setter Property=&quot;Template&quot;&gt;
                &lt;Setter.Value&gt;
                    &lt;ControlTemplate TargetType=&quot;{x:Type CheckBox}&quot;&gt;
                        &lt;BulletDecorator Background=&quot;Transparent&quot;
                                         SnapsToDevicePixels=&quot;true&quot;&gt;
                            &lt;BulletDecorator.Bullet&gt;
                                &lt;Border BorderBrush=&quot;{TemplateBinding BorderBrush}&quot;
                                        Background=&quot;{TemplateBinding Background}&quot;
                                        BorderThickness=&quot;1&quot;
                                        Width=&quot;11&quot; Height=&quot;11&quot; Margin=&quot;0,1,0,0&quot;&gt;
                                    &lt;Grid&gt;
                                        &lt;Path Name=&quot;TickMark&quot;
                                              Fill=&quot;Blue&quot;
                                              Data=&quot;M0,4 5,9 9,0 4,5&quot;
                                              Visibility=&quot;Hidden&quot; /&gt;
                                        &lt;Rectangle Name=&quot;IndeterminateMark&quot;
                                                   Fill=&quot;Blue&quot;
                                                   Width=&quot;7&quot; Height=&quot;7&quot;
                                                   HorizontalAlignment=&quot;Center&quot;
                                                   VerticalAlignment=&quot;Center&quot;
                                                   Visibility=&quot;Hidden&quot; /&gt;
                                    &lt;/Grid&gt;
                                &lt;/Border&gt;
                            &lt;/BulletDecorator.Bullet&gt;
                            &lt;ContentPresenter HorizontalAlignment=&quot;{TemplateBinding HorizontalContentAlignment}&quot;
                                              Margin=&quot;{TemplateBinding Padding}&quot;
                                              RecognizesAccessKey=&quot;True&quot;
                                              SnapsToDevicePixels=&quot;{TemplateBinding SnapsToDevicePixels}&quot;
                                              VerticalAlignment=&quot;{TemplateBinding VerticalContentAlignment}&quot;/&gt;
                        &lt;/BulletDecorator&gt;
                        &lt;ControlTemplate.Triggers&gt;
                            &lt;Trigger Property=&quot;HasContent&quot; Value=&quot;true&quot;&gt;
                                &lt;Setter Property=&quot;FocusVisualStyle&quot; Value=&quot;{StaticResource CheckRadioFocusVisual}&quot;/&gt;
                                &lt;Setter Property=&quot;Padding&quot; Value=&quot;4,0,0,0&quot;/&gt;
                            &lt;/Trigger&gt;
                            &lt;Trigger Property=&quot;IsEnabled&quot; Value=&quot;false&quot;&gt;
                                &lt;Setter Property=&quot;Foreground&quot; Value=&quot;{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}&quot;/&gt;
                            &lt;/Trigger&gt;
                            &lt;Trigger Property=&quot;IsChecked&quot; Value=&quot;True&quot;&gt;
                                &lt;Setter TargetName=&quot;TickMark&quot; Property=&quot;Visibility&quot; Value=&quot;Visible&quot; /&gt;
                            &lt;/Trigger&gt;
                            &lt;Trigger Property=&quot;IsChecked&quot; Value=&quot;{x:Null}&quot;&gt;
                                &lt;Setter TargetName=&quot;IndeterminateMark&quot; Property=&quot;Visibility&quot; Value=&quot;Visible&quot; /&gt;
                            &lt;/Trigger&gt;
                        &lt;/ControlTemplate.Triggers&gt;
                    &lt;/ControlTemplate&gt;
                &lt;/Setter.Value&gt;
            &lt;/Setter&gt;
        &lt;/Style&gt;
        &lt;Style x:Key=&quot;{x:Type RadioButton}&quot; TargetType=&quot;{x:Type RadioButton}&quot;&gt;
            &lt;Setter Property=&quot;Foreground&quot; Value=&quot;{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}&quot;/&gt;
            &lt;Setter Property=&quot;Background&quot; Value=&quot;#F4F4F4&quot;/&gt;
            &lt;Setter Property=&quot;BorderBrush&quot; Value=&quot;{StaticResource CheckBoxStroke}&quot;/&gt;
            &lt;Setter Property=&quot;BorderThickness&quot; Value=&quot;1&quot;/&gt;
            &lt;Setter Property=&quot;Template&quot;&gt;
                &lt;Setter.Value&gt;
                    &lt;ControlTemplate TargetType=&quot;{x:Type RadioButton}&quot;&gt;
                        &lt;BulletDecorator Background=&quot;Transparent&quot;&gt;
                            &lt;BulletDecorator.Bullet&gt;
                                &lt;Grid VerticalAlignment=&quot;Center&quot; Margin=&quot;0,1,0,0&quot;&gt;
                                    &lt;Ellipse Width=&quot;11&quot; Height=&quot;11&quot;
                                             Stroke=&quot;{TemplateBinding BorderBrush}&quot;
                                             StrokeThickness=&quot;1&quot;
                                             Fill=&quot;{TemplateBinding Background}&quot; /&gt;
                                    &lt;Ellipse Name=&quot;TickMark&quot;
                                             Width=&quot;7&quot; Height=&quot;7&quot;
                                             Fill=&quot;Blue&quot;
                                             Visibility=&quot;Hidden&quot; /&gt;
                                    &lt;Ellipse Name=&quot;IndeterminateMark&quot;
                                             Width=&quot;3&quot; Height=&quot;3&quot;
                                             Fill=&quot;Blue&quot;
                                             Visibility=&quot;Hidden&quot; /&gt;
                                &lt;/Grid&gt;
                            &lt;/BulletDecorator.Bullet&gt;
                            &lt;ContentPresenter HorizontalAlignment=&quot;{TemplateBinding HorizontalContentAlignment}&quot;
                                              Margin=&quot;{TemplateBinding Padding}&quot;
                                              RecognizesAccessKey=&quot;True&quot;
                                              VerticalAlignment=&quot;{TemplateBinding VerticalContentAlignment}&quot;/&gt;
                        &lt;/BulletDecorator&gt;
                        &lt;ControlTemplate.Triggers&gt;
                            &lt;Trigger Property=&quot;HasContent&quot; Value=&quot;true&quot;&gt;
                                &lt;Setter Property=&quot;FocusVisualStyle&quot; Value=&quot;{StaticResource CheckRadioFocusVisual}&quot;/&gt;
                                &lt;Setter Property=&quot;Padding&quot; Value=&quot;4,0,0,0&quot;/&gt;
                            &lt;/Trigger&gt;
                            &lt;Trigger Property=&quot;IsEnabled&quot; Value=&quot;false&quot;&gt;
                                &lt;Setter Property=&quot;Foreground&quot; Value=&quot;{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}&quot;/&gt;
                            &lt;/Trigger&gt;
                            &lt;Trigger Property=&quot;IsChecked&quot; Value=&quot;True&quot;&gt;
                                &lt;Setter TargetName=&quot;TickMark&quot; Property=&quot;Visibility&quot; Value=&quot;Visible&quot; /&gt;
                            &lt;/Trigger&gt;
                            &lt;Trigger Property=&quot;IsChecked&quot; Value=&quot;{x:Null}&quot;&gt;
                                &lt;Setter TargetName=&quot;IndeterminateMark&quot; Property=&quot;Visibility&quot; Value=&quot;Visible&quot; /&gt;
                            &lt;/Trigger&gt;
                        &lt;/ControlTemplate.Triggers&gt;
                    &lt;/ControlTemplate&gt;
                &lt;/Setter.Value&gt;
            &lt;/Setter&gt;
        &lt;/Style&gt;
</pre></p>
<p>OK, so you now have beautiful controls that are going to make the app a big success, management is happy, everything is for the best&#8230; until you realize that in another view of the application, the controls need to have the same style, but with green tick marks!</p>
<p>The first solution that comes to mind is to duplicate the style, and replace blue with green in the copy. But since you&#8217;re a good developer who cares about best practices, you know that duplicate code is evil: if you ever need to make changes to the style of the blue <code>CheckBox</code>, you will also have to modify the green one&#8230; and perhaps the red one, and the black one, etc. Clearly it would soon become unmanageable. So we need to refactor, but how? Ideally we would pass parameters to the style, but a style is not a method that you can call with various parameters&#8230;</p>
<p>What we need is an extra property that controls the color of the tick marks, so we can bind to this property in the template. A possible approach is to create custom controls that inherit <code>CheckBox</code> and <code>RadioButton</code>, with an extra <code>TickBrush</code> property&#8230; but personnally I don&#8217;t really like this approach, I always prefer to use the built-in controls when they can fit the bill.</p>
<p>Anyway, there is an easier solution: we just need to create a <code>ThemeProperties</code> class with an attached property of type <code>Brush</code>:</p>
<p><pre class="brush: csharp;">
    public static class ThemeProperties
    {
        public static Brush GetTickBrush(DependencyObject obj)
        {
            return (Brush)obj.GetValue(TickBrushProperty);
        }

        public static void SetTickBrush(DependencyObject obj, Brush value)
        {
            obj.SetValue(TickBrushProperty, value);
        }

        public static readonly DependencyProperty TickBrushProperty =
            DependencyProperty.RegisterAttached(
                &quot;TickBrush&quot;,
                typeof(Brush),
                typeof(ThemeProperties),
                new FrameworkPropertyMetadata(Brushes.Black));
    }
</pre></p>
<p>We change the templates a bit to replace the hard-coded color with a binding to this property:</p>
<p><pre class="brush: xml;">
                                ...

                                &lt;!-- CheckBox --&gt;
                                        &lt;Path Name=&quot;TickMark&quot;
                                              Fill=&quot;{TemplateBinding my:ThemeProperties.TickBrush}&quot;
                                              Data=&quot;M0,4 5,9 9,0 4,5&quot;
                                              Visibility=&quot;Hidden&quot; /&gt;
                                        &lt;Rectangle Name=&quot;IndeterminateMark&quot;
                                                   Fill=&quot;{TemplateBinding my:ThemeProperties.TickBrush}&quot;
                                                   Width=&quot;7&quot; Height=&quot;7&quot;
                                                   HorizontalAlignment=&quot;Center&quot;
                                                   VerticalAlignment=&quot;Center&quot;
                                                   Visibility=&quot;Hidden&quot; /&gt;

                                ...

                                &lt;!-- RadioButton --&gt;
                                    &lt;Ellipse Name=&quot;TickMark&quot;
                                             Width=&quot;7&quot; Height=&quot;7&quot;
                                             Fill=&quot;{TemplateBinding my:ThemeProperties.TickBrush}&quot;
                                             Visibility=&quot;Hidden&quot; /&gt;
                                    &lt;Ellipse Name=&quot;IndeterminateMark&quot;
                                             Width=&quot;3&quot; Height=&quot;3&quot;
                                             Fill=&quot;{TemplateBinding my:ThemeProperties.TickBrush}&quot;
                                             Visibility=&quot;Hidden&quot; /&gt;

</pre></p>
<p>And when we use the controls, we set the property to the desired tick color:</p>
<p><pre class="brush: xml;">
&lt;CheckBox Content=&quot;Checked&quot; IsChecked=&quot;True&quot; my:ThemeProperties.TickBrush=&quot;Blue&quot; /&gt;
</pre></p>
<p>So we can now have controls that share the same style, but have different colors for the tick mark:</p>
<p><a href="http://tomlev.files.wordpress.com/2011/09/parameterized_styles42.png"><img src="http://tomlev.files.wordpress.com/2011/09/parameterized_styles42.png?w=780" alt="" title=""   class="aligncenter size-full wp-image-475" /></a></p>
<p>Isn&#8217;t it great? However there is a small problem left: since controls on the same view all use the same tick color, it&#8217;s not very convenient to repeat the color on each one. It would be nice to be able to specify the color just once, on the root of the view&#8230; Well, as it happens, dependency properties have a nice feature that allows to do exactly that: value inheritance. We just need to specify the <code>Inherits</code> flag in the declaration of the <code>TickBrush</code> property:</p>
<p><pre class="brush: csharp;">
        public static readonly DependencyProperty TickBrushProperty =
            DependencyProperty.RegisterAttached(
                &quot;TickBrush&quot;,
                typeof(Brush),
                typeof(ThemeProperties),
                new FrameworkPropertyMetadata(Brushes.Black, FrameworkPropertyMetadataOptions.Inherits));
</pre></p>
<p>With this flag, the property becomes &#8220;ambient&#8221;: we only need to specify its value on a parent control, and all descendant controls will automatically inherit the value. So if you need a view where all the checkboxes and radiobuttons are red, just set the <code>TickBrush</code> property to <code>Red</code> on the root element of the view.</p>
<p>Obviously this concept can be extended to other cases: actually, every time an element of the template must change based on arbitrary criteria, this technique can be used. It can be a good alternative to duplicating a template when you only need to change a small part of it.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2ftomlev2.wordpress.com%2f2011%2f10%2f01%2fwpf-creating-parameterized-styles-with-attached-properties%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2ftomlev2.wordpress.com%2f2011%2f10%2f01%2fwpf-creating-parameterized-styles-with-attached-properties%2f" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tomlev2.wordpress.com/371/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tomlev2.wordpress.com/371/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tomlev2.wordpress.com/371/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tomlev2.wordpress.com/371/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/tomlev2.wordpress.com/371/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/tomlev2.wordpress.com/371/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/tomlev2.wordpress.com/371/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/tomlev2.wordpress.com/371/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tomlev2.wordpress.com/371/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tomlev2.wordpress.com/371/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tomlev2.wordpress.com/371/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tomlev2.wordpress.com/371/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tomlev2.wordpress.com/371/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tomlev2.wordpress.com/371/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tomlev2.wordpress.com&amp;blog=7442815&amp;post=371&amp;subd=tomlev2&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://tomlev2.wordpress.com/2011/10/01/wpf-creating-parameterized-styles-with-attached-properties/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f4acdb91aba11ddf8f03d4b12453f3d5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tomlev</media:title>
		</media:content>

		<media:content url="http://tomlev.files.wordpress.com/2011/09/parameterized_styles11.png" medium="image" />

		<media:content url="http://tomlev.files.wordpress.com/2011/09/parameterized_styles42.png" medium="image" />

		<media:content url="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2ftomlev2.wordpress.com%2f2011%2f10%2f01%2fwpf-creating-parameterized-styles-with-attached-properties%2f" medium="image">
			<media:title type="html">kick it on DotNetKicks.com</media:title>
		</media:content>
	</item>
		<item>
		<title>[WPF 4.5] Subscribing to an event using a markup extension</title>
		<link>http://tomlev2.wordpress.com/2011/09/23/wpf-4-5-subscribing-to-an-event-using-a-markup-extension/</link>
		<comments>http://tomlev2.wordpress.com/2011/09/23/wpf-4-5-subscribing-to-an-event-using-a-markup-extension/#comments</comments>
		<pubDate>Fri, 23 Sep 2011 11:32:07 +0000</pubDate>
		<dc:creator>Thomas Levesque</dc:creator>
				<category><![CDATA[WPF]]></category>
		<category><![CDATA[.NET 4.5]]></category>
		<category><![CDATA[events]]></category>
		<category><![CDATA[markup extension]]></category>
		<category><![CDATA[XAML]]></category>

		<guid isPermaLink="false">http://tomlev2.wordpress.com/?p=364</guid>
		<description><![CDATA[It&#8217;s been a while since I last wrote about markup extensions&#8230; The release of Visual Studio 11 Developer Preview, which introduces a number of new features to WPF, just gave me a reason to play with them again. The feature I&#8217;m going to discuss here is perhaps not the most impressive, but it fills in [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tomlev2.wordpress.com&amp;blog=7442815&amp;post=364&amp;subd=tomlev2&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s been a while since I last wrote about markup extensions&#8230; The release of <a href="http://msdn.microsoft.com/en-us/vstudio/hh127353">Visual Studio 11 Developer Preview</a>, which introduces a number of <a href="http://msdn.microsoft.com/en-us/library/bb613588%28v=VS.110%29.aspx">new features</a> to WPF, just gave me a reason to play with them again. The feature I&#8217;m going to discuss here is perhaps not the most impressive, but it fills in a gap of the previous versions: the support of markup extensions for events.</p>
<p>Until now, it was possible to use a markup extension in XAML to assign a value to a property, but we couldn&#8217;t do the same to subscribe to an event. In WPF 4.5, it is now possible. So here is a small example of the kind we can do with it&#8230;</p>
<p>When using the MVVM pattern, we often associate commands of the ViewModel with controls of the view, via the binding mechanism. This approach usually works well, but it has some downsides:</p>
<ul>
<li>it introduces a lot of boilerplate code in the ViewModel</li>
<li>not all controls have a <code>Command</code> property (actually, most don&#8217;t), and when this property exists, it corresponds only to one event of the control (e.g. the click on a button). There is no really easy way to &#8220;bind&#8221; the other events to commands of the ViewModel</li>
</ul>
<p>It would be nice to be able to bind events directly to ViewModel methods, like this:</p>
<p><pre class="brush: xml;">
        &lt;Button Content=&quot;Click me&quot;
                Click=&quot;{my:EventBinding OnClick}&quot; /&gt;
</pre><br />
With the <code>OnClick</code> method defined in the ViewModel:<br />
<pre class="brush: csharp;">
        public void OnClick(object sender, EventArgs e)
        {
            MessageBox.Show(&quot;Hello world!&quot;);
        }
</pre></p>
<p>Well, this is now possible! Here&#8217;s a proof of concept&#8230; The <code>EventBindingExtension</code> class shown below first gets the <code>DataContext</code> of the control, then looks for the specified method on the <code>DataContext</code>, and eventually returns a delegate for this method:<br />
<pre class="brush: csharp;">
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Markup;


    public class EventBindingExtension : MarkupExtension
    {
        public EventBindingExtension() { }

        public EventBindingExtension(string eventHandlerName)
        {
            this.EventHandlerName = eventHandlerName;
        }

        [ConstructorArgument(&quot;eventHandlerName&quot;)]
        public string EventHandlerName { get; set; }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            if (string.IsNullOrEmpty(EventHandlerName))
                throw new ArgumentException(&quot;The EventHandlerName property is not set&quot;, &quot;EventHandlerName&quot;);

            var target = (IProvideValueTarget)serviceProvider.GetService(typeof(IProvideValueTarget));

            EventInfo eventInfo = target.TargetProperty as EventInfo;
            if (eventInfo == null)
                throw new InvalidOperationException(&quot;The target property must be an event&quot;);
            
            object dataContext = GetDataContext(target.TargetObject);
            if (dataContext == null)
                throw new InvalidOperationException(&quot;No DataContext found&quot;);

            var handler = GetHandler(dataContext, eventInfo, EventHandlerName);
            if (handler == null)
                throw new ArgumentException(&quot;No valid event handler was found&quot;, &quot;EventHandlerName&quot;);

            return handler;
        }

        #region Helper methods

        static object GetHandler(object dataContext, EventInfo eventInfo, string eventHandlerName)
        {
            Type dcType = dataContext.GetType();

            var method = dcType.GetMethod(
                eventHandlerName,
                GetParameterTypes(eventInfo));
            if (method != null)
            {
                if (method.IsStatic)
                    return Delegate.CreateDelegate(eventInfo.EventHandlerType, method);
                else
                    return Delegate.CreateDelegate(eventInfo.EventHandlerType, dataContext, method);
            }

            return null;
        }

        static Type[] GetParameterTypes(EventInfo eventInfo)
        {
            var invokeMethod = eventInfo.EventHandlerType.GetMethod(&quot;Invoke&quot;);
            return invokeMethod.GetParameters().Select(p =&gt; p.ParameterType).ToArray();
        }

        static object GetDataContext(object target)
        {
            var depObj = target as DependencyObject;
            if (depObj == null)
                return null;

            return depObj.GetValue(FrameworkElement.DataContextProperty)
                ?? depObj.GetValue(FrameworkContentElement.DataContextProperty);
        }

        #endregion
    }
</pre></p>
<p>This class can be used as shown in the example above.</p>
<p>As it is now, this markup extension has an annoying limitation: the <code>DataContext</code> must be set before the call to <code>ProvideValue</code>, otherwise it won&#8217;t be possible to find the event handler method. A solution could be to subscribe to the <code>DataContextChanged</code> event to look for the method after the <code>DataContext</code> is set, but in the meantime we still need to return something&#8230; and we can&#8217;t return null, because it would cause an exception (since you can&#8217;t subscribe to an event with a null handler). So we need to return a dummy handler generated dynamically from the event signature. It makes things a bit harder&#8230; but it&#8217;s still feasible.</p>
<p>Here&#8217;s a second version that implements this improvement :</p>
<p><pre class="brush: csharp; collapse: true; light: false; toolbar: true;">
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Windows;
using System.Windows.Markup;

    public class EventBindingExtension : MarkupExtension
    {
        private EventInfo _eventInfo;

        public EventBindingExtension() { }

        public EventBindingExtension(string eventHandlerName)
        {
            this.EventHandlerName = eventHandlerName;
        }

        [ConstructorArgument(&quot;eventHandlerName&quot;)]
        public string EventHandlerName { get; set; }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            if (string.IsNullOrEmpty(EventHandlerName))
                throw new ArgumentException(&quot;The EventHandlerName property is not set&quot;, &quot;EventHandlerName&quot;);

            var target = (IProvideValueTarget)serviceProvider.GetService(typeof(IProvideValueTarget));

            var targetObj = target.TargetObject as DependencyObject;
            if (targetObj == null)
                throw new InvalidOperationException(&quot;The target object must be a DependencyObject&quot;);

            _eventInfo = target.TargetProperty as EventInfo;
            if (_eventInfo == null)
                throw new InvalidOperationException(&quot;The target property must be an event&quot;);

            object dataContext = GetDataContext(targetObj);
            if (dataContext == null)
            {
                SubscribeToDataContextChanged(targetObj);
                return GetDummyHandler(_eventInfo.EventHandlerType);
            }

            var handler = GetHandler(dataContext, _eventInfo, EventHandlerName);
            if (handler == null)
            {
                Trace.TraceError(
                    &quot;EventBinding: no suitable method named '{0}' found in type '{1}' to handle event '{2'}&quot;,
                    EventHandlerName,
                    dataContext.GetType(),
                    _eventInfo);
                return GetDummyHandler(_eventInfo.EventHandlerType);
            }

            return handler;
            
        }

        #region Helper methods

        static Delegate GetHandler(object dataContext, EventInfo eventInfo, string eventHandlerName)
        {
            Type dcType = dataContext.GetType();

            var method = dcType.GetMethod(
                eventHandlerName,
                GetParameterTypes(eventInfo.EventHandlerType));
            if (method != null)
            {
                if (method.IsStatic)
                    return Delegate.CreateDelegate(eventInfo.EventHandlerType, method);
                else
                    return Delegate.CreateDelegate(eventInfo.EventHandlerType, dataContext, method);
            }

            return null;
        }

        static Type[] GetParameterTypes(Type delegateType)
        {
            var invokeMethod = delegateType.GetMethod(&quot;Invoke&quot;);
            return invokeMethod.GetParameters().Select(p =&gt; p.ParameterType).ToArray();
        }

        static object GetDataContext(DependencyObject target)
        {
            return target.GetValue(FrameworkElement.DataContextProperty)
                ?? target.GetValue(FrameworkContentElement.DataContextProperty);
        }

        static readonly Dictionary&lt;Type, Delegate&gt; _dummyHandlers = new Dictionary&lt;Type, Delegate&gt;();

        static Delegate GetDummyHandler(Type eventHandlerType)
        {
            Delegate handler;
            if (!_dummyHandlers.TryGetValue(eventHandlerType, out handler))
            {
                handler = CreateDummyHandler(eventHandlerType);
                _dummyHandlers[eventHandlerType] = handler;
            }
            return handler;
        }

        static Delegate CreateDummyHandler(Type eventHandlerType)
        {
            var parameterTypes = GetParameterTypes(eventHandlerType);
            var returnType = eventHandlerType.GetMethod(&quot;Invoke&quot;).ReturnType;
            var dm = new DynamicMethod(&quot;DummyHandler&quot;, returnType, parameterTypes);
            var il = dm.GetILGenerator();
            if (returnType != typeof(void))
            {
                if (returnType.IsValueType)
                {
                    var local = il.DeclareLocal(returnType);
                    il.Emit(OpCodes.Ldloca_S, local);
                    il.Emit(OpCodes.Initobj, returnType);
                    il.Emit(OpCodes.Ldloc_0);
                }
                else
                {
                    il.Emit(OpCodes.Ldnull);
                }
            }
            il.Emit(OpCodes.Ret);
            return dm.CreateDelegate(eventHandlerType);
        }

        private void SubscribeToDataContextChanged(DependencyObject targetObj)
        {
            DependencyPropertyDescriptor
                .FromProperty(FrameworkElement.DataContextProperty, targetObj.GetType())
                .AddValueChanged(targetObj, TargetObject_DataContextChanged);
        }

        private void UnsubscribeFromDataContextChanged(DependencyObject targetObj)
        {
            DependencyPropertyDescriptor
                .FromProperty(FrameworkElement.DataContextProperty, targetObj.GetType())
                .RemoveValueChanged(targetObj, TargetObject_DataContextChanged);
        }

        private void TargetObject_DataContextChanged(object sender, EventArgs e)
        {
            DependencyObject targetObj = sender as DependencyObject;
            if (targetObj == null)
                return;

            object dataContext = GetDataContext(targetObj);
            if (dataContext == null)
                return;

            var handler = GetHandler(dataContext, _eventInfo, EventHandlerName);
            if (handler != null)
            {
                _eventInfo.AddEventHandler(targetObj, handler);
            }
            UnsubscribeFromDataContextChanged(targetObj);
        }

        #endregion
    }
</pre></p>
<p>So this is the kind of things we can do thanks to this new WPF feature. We could also imagine a behavior system similar to what we can do with attached properties, e.g. to execute a standard action when an event occurs. There are lots of possible applications for this, I leave it to you to find them <img src='http://s1.wp.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2ftomlev2.wordpress.com%2f2011%2f09%2f23%2fwpf-4-5-subscribing-to-an-event-using-a-markup-extension%2f"><img src="http://dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://tomlev2.wordpress.com/2011/09/23/wpf-4-5-subscribing-to-an-event-using-a-markup-extension/" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tomlev2.wordpress.com/364/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tomlev2.wordpress.com/364/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tomlev2.wordpress.com/364/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tomlev2.wordpress.com/364/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/tomlev2.wordpress.com/364/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/tomlev2.wordpress.com/364/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/tomlev2.wordpress.com/364/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/tomlev2.wordpress.com/364/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tomlev2.wordpress.com/364/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tomlev2.wordpress.com/364/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tomlev2.wordpress.com/364/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tomlev2.wordpress.com/364/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tomlev2.wordpress.com/364/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tomlev2.wordpress.com/364/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tomlev2.wordpress.com&amp;blog=7442815&amp;post=364&amp;subd=tomlev2&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://tomlev2.wordpress.com/2011/09/23/wpf-4-5-subscribing-to-an-event-using-a-markup-extension/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f4acdb91aba11ddf8f03d4b12453f3d5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tomlev</media:title>
		</media:content>

		<media:content url="http://dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://tomlev2.wordpress.com/2011/09/23/wpf-4-5-subscribing-to-an-event-using-a-markup-extension/" medium="image">
			<media:title type="html">kick it on DotNetKicks.com</media:title>
		</media:content>
	</item>
		<item>
		<title>Tail recursion in C#</title>
		<link>http://tomlev2.wordpress.com/2011/09/02/tail-recursion-in-c/</link>
		<comments>http://tomlev2.wordpress.com/2011/09/02/tail-recursion-in-c/#comments</comments>
		<pubDate>Thu, 01 Sep 2011 22:16:52 +0000</pubDate>
		<dc:creator>Thomas Levesque</dc:creator>
				<category><![CDATA[Code sample]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[tail recursion]]></category>
		<category><![CDATA[trampoline]]></category>

		<guid isPermaLink="false">http://tomlev2.wordpress.com/?p=348</guid>
		<description><![CDATA[Regardless of the programming language you&#8217;re using, there are tasks for which the most natural implementation uses a recursive algorithm (even if it&#8217;s not always the optimal solution). The trouble with the recursive approach is that it can use a lot of space on the stack: when you reach a certain recursion depth, the memory [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tomlev2.wordpress.com&amp;blog=7442815&amp;post=348&amp;subd=tomlev2&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Regardless of the programming language you&#8217;re using, there are tasks for which the most natural implementation uses a recursive algorithm (even if it&#8217;s not always the optimal solution). The trouble with the recursive approach is that it can use a lot of space on the stack: when you reach a certain recursion depth, the memory allocated for the thread stack runs out, and you get a stack overflow error that usually terminates the process (<code>StackOverflowException</code> in .NET).</p>
<h6><strong>Terminal recursion? What&#8217;s that?</strong></h6>
<p>Some languages, more particularly functional languages, have native support for an optimization technique called <a href="http://en.wikipedia.org/wiki/Tail_recursion">tail recursion</a>. The idea is that if the recursive call is the last instruction in a recursive function, there is no need to keep the current call context on the stack, since we won&#8217;t have to go back there: we only need to replace the parameters with their new values, and jump back to the beginning of the function. So the recursion is transformed into an iteration, so it can’t cause a stack overflow. This notion being quite new to me, I won’t try to give a full course about tail recursion… much smarter people already took care of it! I suggest you follow the Wikipedia link above, which is a good starting point to understand tail recursion.</p>
<p>Unfortunately, the C# compiler doesn’t support tail recursion, which is a pity, since <a href="http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.tailcall.aspx">the CLR supports it</a>. However, all is not lost! Some people had a very clever idea to work around this issue: a technique called “trampoline” (because it makes the function “bounce”) that allows to easily transform a recursive algorithm into an iterative algorithm. Samuel Jack has a good explanation of this concept <a href="http://blog.functionalfun.net/2008/04/bouncing-on-your-tail.html">on his blog</a>. In the rest of this article, we will see how to apply this technique to a simple algorithm, using the class from Samuel Jack’s article; then I’ll present another implementation of the trampoline, which I find more flexible.</p>
<h6><strong>A simple use case in C#</strong></h6>
<p>Let’s see how we can transform a simple recursive algorithm, like the computation of the factorial of a number, into an algorithm that uses tail recursion (incidentally, the factorial can be computed much more efficiently with a non-recursive algorithm, but let’s assume we don’t know that…). Here’s a basic implementation that results directly from the definition:</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:2aa3986e-d921-4423-8304-e7d6fbc79931" class="wlWriterEditableSmartContent">
<pre style="white-space:normal;">
<pre class="brush: csharp; pad-line-numbers: true;">
BigInteger Factorial(int n)
{
    if (n &lt; 2)
        return 1;
    return n * Factorial(n - 1);
}
</pre>
</pre>
</div>
<p>(Note the use of <code>BigInteger</code>: if we are to make the recursion deep enough to observe the effects of tail recursion, the result will be far beyond the capacity of an int or even a <code>long</code>…)</p>
<p>If we call this method with a large value (around 20000 on my machine), we get an error which was quite predictable: <code>StackOverflowException</code>. We made so many nested call to the <code>Factorial</code> method that we exhausted the capacity of the stack. So we’re going to modify this code so that it can benefit from tail recursion…</p>
<p>As mentioned above, the key requirement for tail recursion is that the method calls itself as the last instruction. It <em>seems</em> to be the case here… but it’s not: the last operation is actually the multiplication, which can’t be executed until we know the result of <code>Factorial(n-1)</code>. So we need to redesign this method so that it ends with a call to itself, with different arguments. To do that, we can add a new parameter named <code>product</code>, which will act as an accumulator:</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:97fbca58-db0a-4d05-b167-8886b0bd2216" class="wlWriterEditableSmartContent">
<pre style="white-space:normal;">
<pre class="brush: csharp;">
BigInteger Factorial(int n, BigInteger product)
{
    if (n &lt; 2)
        return product;
    return Factorial(n - 1, n * product);
}
</pre>
</pre>
</div>
<p>For the first call, we’ll just have to pass 1 for the initial value of the accumulator.</p>
<p>We now have a method that meets the requirements for tail recursion: the recursive call to <code>Factorial</code> really is the last instruction. Now that we have put the algorithm in this form, the final transformation to enable tail recursion using Samuel Jack’s trampoline is trivial:</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:d8fd09ea-5a97-4b30-bff2-d8257bb8e728" class="wlWriterEditableSmartContent">
<pre style="white-space:normal;">
<pre class="brush: csharp;">
Bounce&lt;int, BigInteger, BigInteger&gt; Factorial(int n, BigInteger product)
{
    if (n &lt; 2)
        return Trampoline.ReturnResult&lt;int, BigInteger, BigInteger&gt;(product);
    return Trampoline.Recurse&lt;int, BigInteger, BigInteger&gt;(n - 1, n * product);
}
</pre>
</pre>
</div>
<ul>
<li>Instead of returning the final result directly, we call <code>Trampoline.ReturnResult</code> to tell the trampoline that we now have a result </li>
<li>The recursive call to <code>Factorial</code> is replaced with a call to <code>Trampoline.Recurse</code>, which tells the trampoline that the method needs to be called again with different parameters </li>
</ul>
<p>This method can’t be used directly: it returns a <code>Bounce</code> object, and we don&#8217;t really know what to do with this… To execute it, we use the <code>Trampoline.MakeTrampoline</code> method, which returns a new function on which tail recursion is applied. We can then use this new function directly:</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:8d240a2a-51f4-4ebb-bccb-91a6fc6b0574" class="wlWriterEditableSmartContent">
<pre style="white-space:normal;">
<pre class="brush: csharp;">
Func&lt;int, BigInteger, BigInteger&gt; fact = Trampoline.MakeTrampoline&lt;int, BigInteger, BigInteger&gt;(Factorial);
BigInteger result = fact(50000, 1);
</pre>
</pre>
</div>
<p>We can now compute the factorial of large numbers, with no risk of causing a stack overflow… Admittedly, it’s not very efficient: as mentioned before, there are better ways of computing a factorial, and furthermore, computations involving <code>BigInteger</code>s are much slower than with <code>int</code>s or <code>long</code>s.</p>
<h6><strong>Can we make it better?</strong></h6>
<p>Well, you can guess that I wouldn’t be asking the question unless the answer was yes… The trampoline implementation demonstrated above does its job well enough, but I think it could be made more flexible and easier to use:</p>
<ul>
<li>It only works if you have 2 parameters (of course we can adapt it for a different number of parameters, but then we need to create new methods with adequate signatures for each different arity) </li>
<li>The syntax is quite unwieldy: there are 3 type arguments, and we need to specify them every time because the compiler doesn’t have enough information to infer them automatically </li>
<li>Having to use <code>MakeTrampoline</code> just to create a new function that we can then call isn’t very convenient; it would be more intuitive to have an <code>Execute</code> method that returns the result directly </li>
</ul>
<p>And finally, I think the terminology isn’t very explicit… Names like <code>Trampoline</code> and <code>Bounce</code> sound like fun, but they don’t really reveal the intent.</p>
<p>So I tried to improve the system to make it more convenient. My solution is based on lambda expressions. There is only one type argument (the return type), and the parameters are passed trough a closure, so there is no need for multiple methods to handle different numbers of parameters. Here’s what the <code>Factorial</code> method looks like with my implementation:</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:cd3871c7-a539-4417-be6c-bb82c4e7afde" class="wlWriterEditableSmartContent">
<pre style="white-space:normal;">
<pre class="brush: csharp;">
RecursionResult&lt;BigInteger&gt; Factorial(int n, BigInteger product)
{
    if (n &lt; 2)
        return TailRecursion.Return(product);
    return TailRecursion.Next(() =&gt; Factorial(n - 1, n * product));
}
</pre>
</pre>
</div>
<p>It can be used as follows:</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:29c48110-63b2-41f7-8515-2ea8aaccacda" class="wlWriterEditableSmartContent">
<pre style="white-space:normal;">
<pre class="brush: csharp;">
BigInteger result = TailRecursion.Execute(() =&gt; Factorial(50000, 1));
</pre>
</pre>
</div>
<p>It’s more flexible, more concise, and more readable…in my opinion at least<img style="border-style:none;" class="wlEmoticon wlEmoticon-smile" alt="Sourire" src="http://tomlev2.files.wordpress.com/2011/09/wlemoticon-smile.png?w=780" />. The downside is that performance is slightly worse than before (it takes about 20% longer to compute the factorial of 50000), probably because of the delegate creation at each level of recursion.</p>
<p>Here’s the full code for the <code>TailRecursion</code> class:</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:cd8b671b-f2c3-4e18-8f17-82e7a75140a5" class="wlWriterEditableSmartContent">
<pre style="white-space:normal;">
<pre class="brush: csharp;">
public static class TailRecursion
{
    public static T Execute&lt;T&gt;(Func&lt;RecursionResult&lt;T&gt;&gt; func)
    {
        do
        {
            var recursionResult = func();
            if (recursionResult.IsFinalResult)
                return recursionResult.Result;
            func = recursionResult.NextStep;
        } while (true);
    }

    public static RecursionResult&lt;T&gt; Return&lt;T&gt;(T result)
    {
        return new RecursionResult&lt;T&gt;(true, result, null);
    }

    public static RecursionResult&lt;T&gt; Next&lt;T&gt;(Func&lt;RecursionResult&lt;T&gt;&gt; nextStep)
    {
        return new RecursionResult&lt;T&gt;(false, default(T), nextStep);
    }

}

public class RecursionResult&lt;T&gt;
{
    private readonly bool _isFinalResult;
    private readonly T _result;
    private readonly Func&lt;RecursionResult&lt;T&gt;&gt; _nextStep;
    internal RecursionResult(bool isFinalResult, T result, Func&lt;RecursionResult&lt;T&gt;&gt; nextStep)
    {
        _isFinalResult = isFinalResult;
        _result = result;
        _nextStep = nextStep;
    }

    public bool IsFinalResult { get { return _isFinalResult; } }
    public T Result { get { return _result; } }
    public Func&lt;RecursionResult&lt;T&gt;&gt; NextStep { get { return _nextStep; } }
}
</pre>
</pre>
</div>
<h6><strong>Is there a better way to accomplish tail recursion in C#?</strong></h6>
<p>Sure! But it gets a little tricky, and it’s not pure C#. As I mentioned before, the CLR supports tail recursion, through the <code>tail</code> instruction. Ideally, the C# compiler would automatically generate this instruction for methods that are eligible to tail recursion, but unfortunately it’s not the case, and I don’t think this will ever be supported given the low demand for this feature.</p>
<p>Anyway, we can cheat a little by helping the compiler to do its job: the .NET Framework SDK provides tools named <a href="http://msdn.microsoft.com/en-us/library/f7dy01k1.aspx">ildasm</a> (IL disassembler) and <a href="http://msdn.microsoft.com/en-us/library/496e4ekx.aspx">ilasm</a> (IL assembler), which can help to fill the gap between C# and the CLR… Let’s go back to the classical recursive implementation of <code>Factorial</code>, which doesn’t yet use tail recursion:</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:897629e6-ae6b-4cbe-a500-ce0f179e9b18" class="wlWriterEditableSmartContent">
<pre style="white-space:normal;">
<pre class="brush: csharp;">
static BigInteger Factorial(int n, BigInteger product)
{
	if (n &lt; 2)
		return product;
	return Factorial(n - 1, n * product);
}
</pre>
</pre>
</div>
<p>If we compile this code and disassemble it with ilasm, we get the following IL code:</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:b7c1f693-9c0e-446e-88ea-cff80d96f9d7" class="wlWriterEditableSmartContent">
<pre style="white-space:normal;">
<pre class="brush: plain; wrap-lines: false;">
.method private hidebysig static valuetype [System.Numerics]System.Numerics.BigInteger
        Factorial(int32 n,
                  valuetype [System.Numerics]System.Numerics.BigInteger product) cil managed
{
  // Code size       41 (0x29)
  .maxstack  3
  .locals init (valuetype [System.Numerics]System.Numerics.BigInteger V_0,
           bool V_1)
  IL_0000:  nop
  IL_0001:  ldarg.0
  IL_0002:  ldc.i4.2
  IL_0003:  clt
  IL_0005:  ldc.i4.0
  IL_0006:  ceq
  IL_0008:  stloc.1
  IL_0009:  ldloc.1
  IL_000a:  brtrue.s   IL_0010

  IL_000c:  ldarg.1
  IL_000d:  stloc.0
  IL_000e:  br.s       IL_0027

  IL_0010:  ldarg.0
  IL_0011:  ldc.i4.1
  IL_0012:  sub
  IL_0013:  ldarg.0
  IL_0014:  call       valuetype [System.Numerics]System.Numerics.BigInteger [System.Numerics]System.Numerics.BigInteger::op_Implicit(int32)
  IL_0019:  ldarg.1
  IL_001a:  call       valuetype [System.Numerics]System.Numerics.BigInteger [System.Numerics]System.Numerics.BigInteger::op_Multiply(valuetype [System.Numerics]System.Numerics.BigInteger,
                                                                                                                                      valuetype [System.Numerics]System.Numerics.BigInteger)
  IL_001f:  call       valuetype [System.Numerics]System.Numerics.BigInteger Program::Factorial(int32,
                                                                                                valuetype [System.Numerics]System.Numerics.BigInteger)
  IL_0024:  stloc.0
  IL_0025:  br.s       IL_0027

  IL_0027:  ldloc.0
  IL_0028:  ret
} // end of method Program::Factorial
</pre>
</pre>
</div>
<p>It’s a bit hard on the eye if you’re not used to read IL code, but we can see roughly what’s going on… The recursive call is at offset <code>IL_001f;</code> this is where we’re going to fiddle with the generated code to introduce tail recursion. If we look at the documentation for the <code>tail</code> instruction, we see that it must immediately precede a <code>call</code> instruction, and that the instruction following the <code>call</code> must be <code>ret</code> (return). Right now, we have several instructions following the recursive call, because the compiler introduced a local variable to store the return value. We just need to modify the code so that it doesn’t use this variable, and add the <code>tail</code> instruction in the right place:</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:8f064bd1-b6df-4d38-9356-430fb24e9b2f" class="wlWriterEditableSmartContent">
<pre style="white-space:normal;">
<pre class="brush: plain; wrap-lines: false;">
.method private hidebysig static valuetype [System.Numerics]System.Numerics.BigInteger
        Factorial(int32 n,
                  valuetype [System.Numerics]System.Numerics.BigInteger product) cil managed
{
  // Code size       41 (0x29)
  .maxstack  3
  .locals init (valuetype [System.Numerics]System.Numerics.BigInteger V_0,
           bool V_1)
  IL_0000:  nop
  IL_0001:  ldarg.0
  IL_0002:  ldc.i4.2
  IL_0003:  clt
  IL_0005:  ldc.i4.0
  IL_0006:  ceq
  IL_0008:  stloc.1
  IL_0009:  ldloc.1
  IL_000a:  brtrue.s   IL_0010

  IL_000c:  ldarg.1
  IL_000d:  ret		// Return directly instead of storing the result in V_0
  IL_000e:  nop

  IL_0010:  ldarg.0
  IL_0011:  ldc.i4.1
  IL_0012:  sub
  IL_0013:  ldarg.0
  IL_0014:  call       valuetype [System.Numerics]System.Numerics.BigInteger [System.Numerics]System.Numerics.BigInteger::op_Implicit(int32)
  IL_0019:  ldarg.1
  IL_001a:  call       valuetype [System.Numerics]System.Numerics.BigInteger [System.Numerics]System.Numerics.BigInteger::op_Multiply(valuetype [System.Numerics]System.Numerics.BigInteger,
                                                                                                                                      valuetype [System.Numerics]System.Numerics.BigInteger)
  IL_001f:  tail.
  IL_0020:  call       valuetype [System.Numerics]System.Numerics.BigInteger Program::Factorial(int32,
                                                                                                valuetype [System.Numerics]System.Numerics.BigInteger)
  IL_0025:  ret		// Return directly instead of storing the result in V_0

} // end of method Program::Factorial
</pre>
</pre>
</div>
<p>If we reassemble this code with ilasm, we get a new executable, which runs without issues even for large values which made the old code crash<img style="border-style:none;" class="wlEmoticon wlEmoticon-smile" alt="Sourire" src="http://tomlev2.files.wordpress.com/2011/09/wlemoticon-smile.png?w=780" />. Performance is also pretty good: about 3 times as fast than the version using the <code>Trampoline</code> class. If we compare the performance for smaller values (so that the old code doesn’t crash), we can see that it’s also 3 times as fast as the recursive version with no tail recursion.</p>
<p>Of course, this is just a proof of concept… it doesn’t seem very realistic to perform this transformation manually in a “real” project. However, it might be possible to create a tool that rewrites assemblies automatically after the compilation to introduce tail recursion.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2ftomlev2.wordpress.com%2f2011%2f09%2f02%2ftail-recursion-in-c%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2ftomlev2.wordpress.com%2f2011%2f09%2f02%2ftail-recursion-in-c%2f" border="0" alt="kick it on DotNetKicks.com" /></a> <a rev="vote-for" href="http://dotnetshoutout.com/Tail-recursion-in-C-Thomas-Levesques-NET-blog"><img alt="Shout it" src="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Ftomlev2.wordpress.com%2F2011%2F09%2F02%2Ftail-recursion-in-c%2F" style="border:0;" /></a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tomlev2.wordpress.com/348/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tomlev2.wordpress.com/348/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tomlev2.wordpress.com/348/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tomlev2.wordpress.com/348/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/tomlev2.wordpress.com/348/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/tomlev2.wordpress.com/348/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/tomlev2.wordpress.com/348/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/tomlev2.wordpress.com/348/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tomlev2.wordpress.com/348/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tomlev2.wordpress.com/348/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tomlev2.wordpress.com/348/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tomlev2.wordpress.com/348/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tomlev2.wordpress.com/348/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tomlev2.wordpress.com/348/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tomlev2.wordpress.com&amp;blog=7442815&amp;post=348&amp;subd=tomlev2&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://tomlev2.wordpress.com/2011/09/02/tail-recursion-in-c/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f4acdb91aba11ddf8f03d4b12453f3d5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tomlev</media:title>
		</media:content>

		<media:content url="http://tomlev2.files.wordpress.com/2011/09/wlemoticon-smile.png" medium="image">
			<media:title type="html">Sourire</media:title>
		</media:content>

		<media:content url="http://tomlev2.files.wordpress.com/2011/09/wlemoticon-smile.png" medium="image">
			<media:title type="html">Sourire</media:title>
		</media:content>

		<media:content url="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2ftomlev2.wordpress.com%2f2011%2f09%2f02%2ftail-recursion-in-c%2f" medium="image">
			<media:title type="html">kick it on DotNetKicks.com</media:title>
		</media:content>

		<media:content url="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Ftomlev2.wordpress.com%2F2011%2F09%2F02%2Ftail-recursion-in-c%2F" medium="image">
			<media:title type="html">Shout it</media:title>
		</media:content>
	</item>
		<item>
		<title>[WPF] Display an animated GIF image</title>
		<link>http://tomlev2.wordpress.com/2011/03/27/wpf-display-an-animated-gif-image/</link>
		<comments>http://tomlev2.wordpress.com/2011/03/27/wpf-display-an-animated-gif-image/#comments</comments>
		<pubDate>Sun, 27 Mar 2011 22:25:18 +0000</pubDate>
		<dc:creator>Thomas Levesque</dc:creator>
				<category><![CDATA[WPF]]></category>
		<category><![CDATA[animated]]></category>
		<category><![CDATA[gif]]></category>

		<guid isPermaLink="false">http://tomlev2.wordpress.com/?p=336</guid>
		<description><![CDATA[WPF is a great technology, but sometimes it seems to be missing some really basic features&#8230; A frequently mentioned example is the lack of support for animated GIF images. Actually, the GIF format itself is supported by the imaging API, but the Image control only shows the first frame of the animation. Many solutions to [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tomlev2.wordpress.com&amp;blog=7442815&amp;post=336&amp;subd=tomlev2&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>WPF is a great technology, but sometimes it seems to be missing some really basic features&#8230; A frequently mentioned example is the lack of support for animated GIF images. Actually, the GIF format itself is supported by the imaging API, but the <code>Image</code> control only shows the first frame of the animation.</p>
<p>Many solutions to this problem have been proposed on technical forums and blogs, usually variations of the following approaches:</p>
<ul>
<li>Use the <code>MediaElement</code> control: unfortunately this control only supports URI like <code>file://</code> or <code>http://</code>, not the <code>pack://</code> URI schema used for WPF resources; this means the image can&#8217;t be included in the resources, it has to be in a separate file. Furthermore, transparency for GIF images isn&#8217;t supported in <code>MediaElement</code>, which makes the final result quite ugly</li>
<li>Use the <code>PictureBox</code> control from Windows Forms, via a <code>WindowsFormsHost</code>: I personnally dislike using WinForms controls in WPF, it really looks like a hack&#8230;</li>
<li>Create a custom control that inherits <code>Image</code> and handles the animation. Some solutions take advantage of the <code>ImageAnimator</code> class from <code>System.Drawing</code> (GDI), others use a WPF animation to change the current frame. It&#8217;s a rather &#8220;clean&#8221; approach, but it forces you to use a specific control for GIF images. Also, the solution using <code>ImageAnimator</code> turns out not to be very smooth, the animation is quite jerky.</li>
</ul>
<p>As you might have guessed, I don&#8217;t find any of these solutions really satisfying&#8230; Furthermore, none of the implementations I&#8217;ve seen of the third approach handles the duration of each frame properly, they only assume that all frames last 100ms (which is almost always true, but <em>almost</em> isn&#8217;t good enough IMHO&#8230;). So I kept the best ideas from each approach I&#8217;ve seen, and I came up with my own solution. Here are the goals I set to attain:</p>
<ul>
<li>No dependency on Windows Forms or GDI</li>
<li>Display the animated image in a standard <code>Image</code> control</li>
<li>Use the same XAML code for normal and animated images</li>
<li>Support for transparency</li>
<li>Correct handling of frame duration</li>
</ul>
<p>To achieve this result, I started from a very simple, even obvious idea: to animate the image, all you have to do is apply an animation to the <code>Source</code> property of the <code>Image</code> control. WPF provides all the necessary tools to do that; in this case, the <a href="http://msdn.microsoft.com/en-us/library/system.windows.media.animation.objectanimationusingkeyframes.aspx"><code>ObjectAnimationUsingKeyFrames</code></a> class fits the bill perfectly: it allows to specify at what exact time a given value should be assigned to the property, which makes it easy to take the frame duration into account.</p>
<p>The next problem is to extract the frames from the image: fortunately WPF supports this natively, and the <a href="http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapdecoder.aspx"><code>BitmapDecoder</code></a> class provides a <code>Frames</code> property to do exactly that. So, no big difficulty so far&#8230;</p>
<p>Finally, last obstacle: extract the duration of each frame. It&#8217;s the part that took me the longest, because I needed to do some research&#8230; I first thought I would need to read the file manually and decode the binary data myself. But eventually the solution is quite simple, and takes advantage of the <a href="http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapmetadata.aspx"><code>BitmapMetadata</code></a> class. The only difficulty has been to find the &#8220;path&#8221; of the metadata that contains the delay, but after a few minutes of trial and error, here it is: <code>/grctlext/Delay</code>.</p>
<p>The final solution is implemented as an attached property named <code>AnimatedSource</code>, that applies to the <code>Image</code> control, and can be used instead of <code>Source</code>:</p>
<p><pre class="brush: xml;">&lt;Image Stretch=&quot;None&quot; my:ImageBehavior.AnimatedSource=&quot;/Images/animation.gif&quot; /&gt;</pre></p>
<p>This property can also be assigned a normal (not animated) image, it will be displayed normally; therefore this property can be used without worrying about whether the image to display will be animated or not.</p>
<p>So in the end, all the goals have been achieved, and we even get some icing on the cake: this solution also works in the designer (at least in Visual Studio 2010), so the animation is immediately visible when you set the <code>AnimatedSource</code> property <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Without further ado, here&#8217;s the complete code:</p>
<p><pre class="brush: csharp; collapse: true; light: false; toolbar: true;">
    public static class ImageBehavior
    {
        #region AnimatedSource

        [AttachedPropertyBrowsableForType(typeof(Image))]
        public static ImageSource GetAnimatedSource(Image obj)
        {
            return (ImageSource)obj.GetValue(AnimatedSourceProperty);
        }

        public static void SetAnimatedSource(Image obj, ImageSource value)
        {
            obj.SetValue(AnimatedSourceProperty, value);
        }

        public static readonly DependencyProperty AnimatedSourceProperty =
            DependencyProperty.RegisterAttached(
              &quot;AnimatedSource&quot;,
              typeof(ImageSource),
              typeof(ImageBehavior),
              new UIPropertyMetadata(
                null,
                AnimatedSourceChanged));

        private static void AnimatedSourceChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
        {
            Image imageControl = o as Image;
            if (imageControl == null)
                return;

            var oldValue = e.OldValue as ImageSource;
            var newValue = e.NewValue as ImageSource;
            if (oldValue != null)
            {
                imageControl.BeginAnimation(Image.SourceProperty, null);
            }
            if (newValue != null)
            {
                imageControl.DoWhenLoaded(InitAnimationOrImage);
            }
        }

        private static void InitAnimationOrImage(Image imageControl)
        {
            BitmapSource source = GetAnimatedSource(imageControl) as BitmapSource;
            if (source != null)
            {
                var decoder = GetDecoder(source) as GifBitmapDecoder;
                if (decoder != null &amp;&amp; decoder.Frames.Count &gt; 1)
                {
                    var animation = new ObjectAnimationUsingKeyFrames();
                    var totalDuration = TimeSpan.Zero;
                    BitmapSource prevFrame = null;
                    FrameInfo prevInfo = null;
                    foreach (var rawFrame in decoder.Frames)
                    {
                        var info = GetFrameInfo(rawFrame);
                        var frame = MakeFrame(
                            source,
                            rawFrame, info,
                            prevFrame, prevInfo);

                        var keyFrame = new DiscreteObjectKeyFrame(frame, totalDuration);
                        animation.KeyFrames.Add(keyFrame);
                        
                        totalDuration += info.Delay;
                        prevFrame = frame;
                        prevInfo = info;
                    }
                    animation.Duration = totalDuration;
                    animation.RepeatBehavior = RepeatBehavior.Forever;
                    if (animation.KeyFrames.Count &gt; 0)
                        imageControl.Source = (ImageSource)animation.KeyFrames[0].Value;
                    else
                        imageControl.Source = decoder.Frames[0];
                    imageControl.BeginAnimation(Image.SourceProperty, animation);
                    return;
                }
            }
            imageControl.Source = source;
            return;
        }

        private static BitmapDecoder GetDecoder(BitmapSource image)
        {
            BitmapDecoder decoder = null;
            var frame = image as BitmapFrame;
            if (frame != null)
                decoder = frame.Decoder;

            if (decoder == null)
            {
                var bmp = image as BitmapImage;
                if (bmp != null)
                {
                    if (bmp.StreamSource != null)
                    {
                        decoder = BitmapDecoder.Create(bmp.StreamSource, bmp.CreateOptions, bmp.CacheOption);
                    }
                    else if (bmp.UriSource != null)
                    {
                        Uri uri = bmp.UriSource;
                        if (bmp.BaseUri != null &amp;&amp; !uri.IsAbsoluteUri)
                            uri = new Uri(bmp.BaseUri, uri);
                        decoder = BitmapDecoder.Create(uri, bmp.CreateOptions, bmp.CacheOption);
                    }
                }
            }

            return decoder;
        }

        private static BitmapSource MakeFrame(
            BitmapSource fullImage,
            BitmapSource rawFrame, FrameInfo frameInfo,
            BitmapSource previousFrame, FrameInfo previousFrameInfo)
        {
            DrawingVisual visual = new DrawingVisual();
            using (var context = visual.RenderOpen())
            {
                if (previousFrameInfo != null &amp;&amp; previousFrame != null &amp;&amp;
                    previousFrameInfo.DisposalMethod == FrameDisposalMethod.Combine)
                {
                    var fullRect = new Rect(0, 0, fullImage.PixelWidth, fullImage.PixelHeight);
                    context.DrawImage(previousFrame, fullRect);
                }

                context.DrawImage(rawFrame, frameInfo.Rect);
            }
            var bitmap = new RenderTargetBitmap(
                fullImage.PixelWidth, fullImage.PixelHeight,
                fullImage.DpiX, fullImage.DpiY,
                PixelFormats.Pbgra32);
            bitmap.Render(visual);
            return bitmap;
        }

        private class FrameInfo
        {
            public TimeSpan Delay { get; set; }
            public FrameDisposalMethod DisposalMethod { get; set; }
            public double Width { get; set; }
            public double Height { get; set; }
            public double Left { get; set; }
            public double Top { get; set; }

            public Rect Rect
            {
                get { return new Rect(Left, Top, Width, Height); }
            }
        }

        private enum FrameDisposalMethod
        {
            Replace = 0,
            Combine = 1,
            RestoreBackground = 2,
            RestorePrevious = 3
        }

        private static FrameInfo GetFrameInfo(BitmapFrame frame)
        {
            var frameInfo = new FrameInfo
            {
                Delay = TimeSpan.FromMilliseconds(100),
                DisposalMethod = FrameDisposalMethod.Replace,
                Width = frame.PixelWidth,
                Height = frame.PixelHeight,
                Left = 0,
                Top = 0
            };

            BitmapMetadata metadata;
            try
            {
                metadata = frame.Metadata as BitmapMetadata;
                if (metadata != null)
                {
                    const string delayQuery = &quot;/grctlext/Delay&quot;;
                    const string disposalQuery = &quot;/grctlext/Disposal&quot;;
                    const string widthQuery = &quot;/imgdesc/Width&quot;;
                    const string heightQuery = &quot;/imgdesc/Height&quot;;
                    const string leftQuery = &quot;/imgdesc/Left&quot;;
                    const string topQuery = &quot;/imgdesc/Top&quot;;

                    var delay = metadata.GetQueryOrNull&lt;ushort&gt;(delayQuery);
                    if (delay.HasValue)
                        frameInfo.Delay = TimeSpan.FromMilliseconds(10 * delay.Value);

                    var disposal = metadata.GetQueryOrNull&lt;byte&gt;(disposalQuery);
                    if (disposal.HasValue)
                        frameInfo.DisposalMethod = (FrameDisposalMethod) disposal.Value;

                    var width = metadata.GetQueryOrNull&lt;ushort&gt;(widthQuery);
                    if (width.HasValue)
                        frameInfo.Width = width.Value;

                    var height = metadata.GetQueryOrNull&lt;ushort&gt;(heightQuery);
                    if (height.HasValue)
                        frameInfo.Height = height.Value;

                    var left = metadata.GetQueryOrNull&lt;ushort&gt;(leftQuery);
                    if (left.HasValue)
                        frameInfo.Left = left.Value;

                    var top = metadata.GetQueryOrNull&lt;ushort&gt;(topQuery);
                    if (top.HasValue)
                        frameInfo.Top = top.Value;
                }
            }
            catch (NotSupportedException)
            {
            }

            return frameInfo;
        }

        private static T? GetQueryOrNull&lt;T&gt;(this BitmapMetadata metadata, string query)
            where T : struct
        {
            if (metadata.ContainsQuery(query))
            {
                object value = metadata.GetQuery(query);
                if (value != null)
                    return (T) value;
            }
            return null;
        }

        #endregion
    }
</pre></p>
<p>And here&#8217;s the <code>DoWhenLoaded</code> extension method used in the code above:</p>
<p><pre class="brush: csharp;">
public static void DoWhenLoaded&lt;T&gt;(this T element, Action&lt;T&gt; action)
    where T : FrameworkElement
{
    if (element.IsLoaded)
    {
        action(element);
    }
    else
    {
        RoutedEventHandler handler = null;
        handler = (sender, e) =&gt;
        {
            element.Loaded -= handler;
            action(element);
        };
        element.Loaded += handler;
    }
}
</pre></p>
<p>Enjoy <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><strong>Update</strong>: the code that retrieves the frame duration only works on Windows Seven, and on Windows Vista if the <a href="http://support.microsoft.com/kb/971644/en-us">Platform Update</a> is installed (untested). The default duration (100ms) will be used instead on other versions of Windows. I will update the article if I find a solution that works on all operating systems (I know I could use <code>System.Drawing.Bitmap</code>, but I&#8217;d rather not depend on this&#8230;)</p>
<p><strong>Update 2</strong>: as pointed out by Klaus in the comments, the <code>ImageBehavior</code> class didn&#8217;t handle some important attributes of the frames: the diposal method (whether a frame should entirely replace the previous one, or be combined with it), and the frame position (Left/Top/Width/Height). I updated the code to handle these attributes properly. Thank you Klaus!</p>
<p><strong>Update 3</strong>: a commenter on the French version of my blog pointed out a problem when the AnimatedSource is an image in a resource dictionary; the UriSource wasn&#8217;t correctly interpreted when it was a relative URI. This problem is now fixed. Thank you, &#8220;anonymous&#8221;!</p>
<p><strong>Update 4</strong>: uploaded an <a href="http://tlevesque.developpez.com/files/AnimatedGif.zip">example project</a> to demonstrate the code.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2ftomlev2.wordpress.com%2f2011%2f03%2f27%2fwpf-display-an-animated-gif-image%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://tomlev2.wordpress.com/2011/03/27/wpf-display-an-animated-gif-image/" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tomlev2.wordpress.com/336/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tomlev2.wordpress.com/336/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tomlev2.wordpress.com/336/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tomlev2.wordpress.com/336/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/tomlev2.wordpress.com/336/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/tomlev2.wordpress.com/336/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/tomlev2.wordpress.com/336/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/tomlev2.wordpress.com/336/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tomlev2.wordpress.com/336/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tomlev2.wordpress.com/336/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tomlev2.wordpress.com/336/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tomlev2.wordpress.com/336/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tomlev2.wordpress.com/336/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tomlev2.wordpress.com/336/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tomlev2.wordpress.com&amp;blog=7442815&amp;post=336&amp;subd=tomlev2&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://tomlev2.wordpress.com/2011/03/27/wpf-display-an-animated-gif-image/feed/</wfw:commentRss>
		<slash:comments>43</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f4acdb91aba11ddf8f03d4b12453f3d5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tomlev</media:title>
		</media:content>

		<media:content url="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://tomlev2.wordpress.com/2011/03/27/wpf-display-an-animated-gif-image/" medium="image">
			<media:title type="html">kick it on DotNetKicks.com</media:title>
		</media:content>
	</item>
		<item>
		<title>[WPF] How to bind to data when the DataContext is not inherited</title>
		<link>http://tomlev2.wordpress.com/2011/03/21/wpf-how-to-bind-to-data-when-the-datacontext-is-not-inherited/</link>
		<comments>http://tomlev2.wordpress.com/2011/03/21/wpf-how-to-bind-to-data-when-the-datacontext-is-not-inherited/#comments</comments>
		<pubDate>Mon, 21 Mar 2011 16:15:29 +0000</pubDate>
		<dc:creator>Thomas Levesque</dc:creator>
				<category><![CDATA[Tricks]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[binding]]></category>
		<category><![CDATA[datacontext]]></category>
		<category><![CDATA[freezable]]></category>

		<guid isPermaLink="false">http://tomlev2.wordpress.com/?p=327</guid>
		<description><![CDATA[The DataContext property in WPF is extremely handy, because it is automatically inherited by all children of the element where you assign it; therefore you don&#8217;t need to set it again on each element you want to bind. However, in some cases the DataContext is not accessible: it happens for elements that are not part [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tomlev2.wordpress.com&amp;blog=7442815&amp;post=327&amp;subd=tomlev2&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>The <code>DataContext</code> property in WPF is extremely handy, because it is automatically inherited by all children of the element where you assign it; therefore you don&#8217;t need to set it again on each element you want to bind. However, in some cases the <code>DataContext</code> is not accessible: it happens for elements that are not part of the visual or logical tree. It can be very difficult then to bind a property on those elements&#8230;</p>
<p>Let&#8217;s illustrate with a simple example: we want to display a list of products in a <code>DataGrid</code>. In the grid, we want to be able to show or hide the Price column, based on the value of a <code>ShowPrice</code> property exposed by the ViewModel. The obvious approach is to bind the <code>Visibility</code> of the column to the <code>ShowPrice</code> property:</p>
<p><pre class="brush: xml;">
&lt;DataGridTextColumn Header=&quot;Price&quot; Binding=&quot;{Binding Price}&quot; IsReadOnly=&quot;False&quot;
                    Visibility=&quot;{Binding ShowPrice,
                        Converter={StaticResource visibilityConverter}}&quot;/&gt;
</pre></p>
<p>Unfortunately, changing the value of <code>ShowPrice</code> has no effect, and the column is always visible&#8230; why? If we look at the Output window in Visual Studio, we notice the following line:</p>
<blockquote><p>System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=ShowPrice; DataItem=null; target element is &#8216;DataGridTextColumn&#8217; (HashCode=32685253); target property is &#8216;Visibility&#8217; (type &#8216;Visibility&#8217;)</p></blockquote>
<p>The message is rather cryptic, but the meaning is actually quite simple: WPF doesn&#8217;t know which <code>FrameworkElement</code> to use to get the <code>DataContext</code>, because the column doesn&#8217;t belong to the visual or logical tree of the <code>DataGrid</code>.</p>
<p>We can try to tweak the binding to get the desired result, for instance by setting the RelativeSource to the <code>DataGrid</code> itself:</p>
<p><pre class="brush: xml;">
&lt;DataGridTextColumn Header=&quot;Price&quot; Binding=&quot;{Binding Price}&quot; IsReadOnly=&quot;False&quot;
                    Visibility=&quot;{Binding DataContext.ShowPrice,
                        Converter={StaticResource visibilityConverter},
                        RelativeSource={RelativeSource FindAncestor, AncestorType=DataGrid}}&quot;/&gt;
</pre></p>
<p>Or we can add a <code>CheckBox</code> bound to <code>ShowPrice</code>, and try to bind the column visibility to the <code>IsChecked</code> property by specifying the element name:</p>
<p><pre class="brush: xml;">
&lt;DataGridTextColumn Header=&quot;Price&quot; Binding=&quot;{Binding Price}&quot; IsReadOnly=&quot;False&quot;
                    Visibility=&quot;{Binding IsChecked,
                        Converter={StaticResource visibilityConverter},
                        ElementName=chkShowPrice}&quot;/&gt;
</pre></p>
<p>But none of these workarounds seems to work, we always get the same result&#8230;</p>
<p>At this point, it seems that the only viable approach would be to change the column visibility in code-behind, which we usually prefer to avoid when using the MVVM pattern&#8230; But I&#8217;m not going to give up so soon, at least not while there are other options to consider <img src='http://s1.wp.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>The solution to our problem is actually quite simple, and takes advantage of the <a href="http://msdn.microsoft.com/en-us/library/system.windows.freezable.aspx"><code>Freezable</code></a> class. The primary purpose of this class is to define objects that have a modifiable and a read-only state, but the interesting feature in our case is that <code>Freezable</code> objects can inherit the <code>DataContext</code> even when they&#8217;re not in the visual or logical tree. I don&#8217;t know the exact mechanism that enables this behavior, but we&#8217;re going to take advantage of it to make our binding work&#8230;</p>
<p>The idea is to create a class (I called it <code>BindingProxy</code> for reasons that should become obvious very soon) that inherits <code>Freezable</code> and declares a <code>Data</code> dependency property:</p>
<p><pre class="brush: csharp;">
    public class BindingProxy : Freezable
    {
        #region Overrides of Freezable

        protected override Freezable CreateInstanceCore()
        {
            return new BindingProxy();
        }

        #endregion

        public object Data
        {
            get { return (object)GetValue(DataProperty); }
            set { SetValue(DataProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Data.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty DataProperty =
            DependencyProperty.Register(&quot;Data&quot;, typeof(object), typeof(BindingProxy), new UIPropertyMetadata(null));
    }
</pre></p>
<p>We can then declare an instance of this class in the resources of the <code>DataGrid</code>, and bind the <code>Data</code> property to the current <code>DataContext</code>:</p>
<p><pre class="brush: xml;">
&lt;DataGrid.Resources&gt;
    &lt;local:BindingProxy x:Key=&quot;proxy&quot; Data=&quot;{Binding}&quot; /&gt;
&lt;/DataGrid.Resources&gt;
</pre></p>
<p>The last step is to specify this <code>BindingProxy</code> object (easily accessible with <code>StaticResource</code>) as the <code>Source</code> for the binding:</p>
<p><pre class="brush: xml;">
&lt;DataGridTextColumn Header=&quot;Price&quot; Binding=&quot;{Binding Price}&quot; IsReadOnly=&quot;False&quot;
                    Visibility=&quot;{Binding Data.ShowPrice,
                        Converter={StaticResource visibilityConverter},
                        Source={StaticResource proxy}}&quot;/&gt;
</pre></p>
<p>Note that the binding path has been prefixed with &#8220;Data&#8221;, since the path is now relative to the <code>BindingProxy</code> object.</p>
<p>The binding now works correctly, and the column is properly shown or hidden based on the <code>ShowPrice</code> property.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http://tomlev2.wordpress.com/2011/03/21/wpf-how-to-bind-to-data-when-the-datacontext-is-not-inherited/"><img src="http://dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://tomlev2.wordpress.com/2011/03/21/wpf-how-to-bind-to-data-when-the-datacontext-is-not-inherited/" /></a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tomlev2.wordpress.com/327/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tomlev2.wordpress.com/327/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tomlev2.wordpress.com/327/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tomlev2.wordpress.com/327/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/tomlev2.wordpress.com/327/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/tomlev2.wordpress.com/327/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/tomlev2.wordpress.com/327/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/tomlev2.wordpress.com/327/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tomlev2.wordpress.com/327/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tomlev2.wordpress.com/327/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tomlev2.wordpress.com/327/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tomlev2.wordpress.com/327/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tomlev2.wordpress.com/327/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tomlev2.wordpress.com/327/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tomlev2.wordpress.com&amp;blog=7442815&amp;post=327&amp;subd=tomlev2&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://tomlev2.wordpress.com/2011/03/21/wpf-how-to-bind-to-data-when-the-datacontext-is-not-inherited/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f4acdb91aba11ddf8f03d4b12453f3d5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tomlev</media:title>
		</media:content>

		<media:content url="http://dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://tomlev2.wordpress.com/2011/03/21/wpf-how-to-bind-to-data-when-the-datacontext-is-not-inherited/" medium="image" />
	</item>
		<item>
		<title>[Entity Framework] Using Include with lambda expressions</title>
		<link>http://tomlev2.wordpress.com/2010/10/03/entity-framework-using-include-with-lambda-expressions/</link>
		<comments>http://tomlev2.wordpress.com/2010/10/03/entity-framework-using-include-with-lambda-expressions/#comments</comments>
		<pubDate>Sun, 03 Oct 2010 22:42:02 +0000</pubDate>
		<dc:creator>Thomas Levesque</dc:creator>
				<category><![CDATA[C# 4.0]]></category>
		<category><![CDATA[Code sample]]></category>
		<category><![CDATA[.NET 4.0]]></category>
		<category><![CDATA[entity framework]]></category>
		<category><![CDATA[expression]]></category>
		<category><![CDATA[include]]></category>
		<category><![CDATA[lambda]]></category>
		<category><![CDATA[linq]]></category>

		<guid isPermaLink="false">http://tomlev2.wordpress.com/?p=316</guid>
		<description><![CDATA[I&#8217;m currently working on a project that uses Entity Framework 4. Even though lazy loading is enabled, I often use the ObjectQuery.Include method to eagerly load associated entities, in order to avoid database roundtrips when I access them: Or if I also want to eagerly load the product: However, there&#8217;s something that really bothers me [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tomlev2.wordpress.com&amp;blog=7442815&amp;post=316&amp;subd=tomlev2&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m currently working on a project that uses Entity Framework 4. Even though lazy loading is enabled, I often use the <a href="http://msdn.microsoft.com/en-us/library/bb738708.aspx"><code>ObjectQuery.Include</code></a> method to eagerly load associated entities, in order to avoid database roundtrips when I access them:</p>
<p><pre class="brush: csharp;">
var query =
    from ord in db.Orders.Include(&quot;OrderDetails&quot;)
    where ord.Date &gt;= DateTime.Today
    select ord;
</pre></p>
<p>Or if I also want to eagerly load the product:</p>
<p><pre class="brush: csharp;">
var query =
    from ord in db.Orders.Include(&quot;OrderDetails.Product&quot;)
    where ord.Date &gt;= DateTime.Today
    select ord;
</pre></p>
<p>However, there&#8217;s something that really bothers me with this <code>Include</code> method: the property path is passed as a string. This approach has two major drawbacks:</p>
<ul>
<li>It&#8217;s easy to make a mistake when typing the property path, and since it&#8217;s a string, the compiler doesn&#8217;t complain. So we get a runtime error, rather than a compilation error.</li>
<li>We can&#8217;t take advantage of IDE features like Intellisense and refactoring. If we rename a property in the model, automatic refactoring won&#8217;t check the content of the string. We have to manually update all calls to <code>Include</code> that refer to this property, with the risk of missing some of them in the process&#8230;</li>
</ul>
<p>It would be much more convenient to use a lambda expression to specify the property path. The principle is well known, and frequently used to avoid using a string to refer to a property.</p>
<p>The trivial case, where the property to include is directly accessible from the source, is pretty easy to handle, and many implementation can be found on the Internet. We just need to use a method that extracts the property name from an expression :</p>
<p><pre class="brush: csharp;">
    public static class ObjectQueryExtensions
    {
        public static ObjectQuery&lt;T&gt; Include&lt;T&gt;(this ObjectQuery&lt;T&gt; query, Expression&lt;Func&lt;T, object&gt;&gt; selector)
        {
            string propertyName = GetPropertyName(selector);
            return query.Include(propertyName);
        }

        private static string GetPropertyName&lt;T&gt;(Expression&lt;Func&lt;T, object&gt;&gt; expression)
        {
            MemberExpression memberExpr = expression.Body as MemberExpression;
            if (memberExpr == null)
                throw new ArgumentException(&quot;Expression body must be a member expression&quot;);
            return memberExpr.Member.Name;
        }
    }
</pre></p>
<p>Using that extension method, the code from the first sample can be rewritten as follows:</p>
<p><pre class="brush: csharp;">
var query =
    from ord in db.Orders.Include(o =&gt; o.OrderDetails)
    where ord.Date &gt;= DateTime.Today
    select ord;
</pre></p>
<p>This code works fine, but only for the simplest cases&#8230; In the second example, we also want to eagerly load the <code>OrderDetail.Product</code> property, but the code above can&#8217;t handle that case. Indeed, the expression we would use to include the <code>Product</code> property would be something like <code>o.OrderDetails.Select(od =&gt; od.Product)</code>, but the <code>GetPropertyName</code> method can only handle property accesses, not method calls, and it works only for an expression with a single level.</p>
<p>To get the full path of the property to include, we have to walk through the whole expression tree to extract the name of each property. It sounds like a complicated task, but there&#8217;s a class that can help us with it: <a href="http://msdn.microsoft.com/en-us/library/system.linq.expressions.expressionvisitor.aspx"><code>ExpressionVisitor</code></a>. This class was introduced in .NET 4.0 and implements the Visitor pattern to walk through all nodes in the expression tree. It&#8217;s just a base class for implementing custom visitors, and it does nothing else than just visiting each node. All we need to do is inherit it, and override some methods to extract the properties from the expression. Here are the methods we need to override:</p>
<ul>
<li><code>VisitMember</code> : used to visit a property or field access</li>
<li><code>VisitMethodCall</code> : used to visit a method call. Even though method calls aren&#8217;t directly related to what we want to do, we need to change its behavior in the case of Linq operators: the default implementation visits each parameter in their normal order, but for extension method like <code>Select</code> or <code>SelectMany</code>, we need to visit the first parameter (the <code>this</code> parameter) last, so that we retrieve the properties in the correct order.
<p>Here&#8217;s a new version of the <code>Include</code> method, along with the <code>ExpressionVisitor</code> implementation:</p>
<p><pre class="brush: csharp;">
    public static class ObjectQueryExtensions
    {
        public static ObjectQuery&lt;T&gt; Include&lt;T&gt;(this ObjectQuery&lt;T&gt; query, Expression&lt;Func&lt;T, object&gt;&gt; selector)
        {
            string path = new PropertyPathVisitor().GetPropertyPath(selector);
            return query.Include(path);
        }

        class PropertyPathVisitor : ExpressionVisitor
        {
            private Stack&lt;string&gt; _stack;

            public string GetPropertyPath(Expression expression)
            {
                _stack = new Stack&lt;string&gt;();
                Visit(expression);
                return _stack
                    .Aggregate(
                        new StringBuilder(),
                        (sb, name) =&gt;
                            (sb.Length &gt; 0 ? sb.Append(&quot;.&quot;) : sb).Append(name))
                    .ToString();
            }

            protected override Expression VisitMember(MemberExpression expression)
            {
                if (_stack != null)
                    _stack.Push(expression.Member.Name);
                return base.VisitMember(expression);
            }

            protected override Expression VisitMethodCall(MethodCallExpression expression)
            {
                if (IsLinqOperator(expression.Method))
                {
                    for (int i = 1; i &lt; expression.Arguments.Count; i++)
                    {
                        Visit(expression.Arguments[i]);
                    }
                    Visit(expression.Arguments[0]);
                    return expression;
                }
                return base.VisitMethodCall(expression);
            }

            private static bool IsLinqOperator(MethodInfo method)
            {
                if (method.DeclaringType != typeof(Queryable) &amp;&amp; method.DeclaringType != typeof(Enumerable))
                    return false;
                return Attribute.GetCustomAttribute(method, typeof(ExtensionAttribute)) != null;
            }
        }
    }
</pre></p>
<p>I already talked about the <code>VisitMethodCall</code> method, so I won&#8217;t explain it further. The implementation of <code>VisitMember</code> is very simple: we just push the member name on a stack. Why a stack ? That&#8217;s because the expression is not visited in the order one would intuitively expect. For instance, in an expression like <code>o.OrderDetails.Select(od =&gt; od.Product)</code>, the first visited node is not <code>o</code> but the call to <code>Select</code>, because what precedes it (<code>o.OrderDetails</code>) is actually the first parameter of the static <code>Select</code> method&#8230; To retrieve the properties in the correct order, we put them on a stack so that we can read them back in reverse order when we need to build the property path.</p>
<p>The <code>GetPropertyPath</code> method probably doesn&#8217;t need a long explanation: it initializes the stack, visits the expression, and builds the property path from the stack.</p>
<p>We can now rewrite the code from the second example as follows:</p>
<p><pre class="brush: csharp;">
var query =
    from ord in db.Orders.Include(o =&gt; OrderDetails.Select(od =&gt; od.Product))
    where ord.Date &gt;= DateTime.Today
    select ord;
</pre></p>
<p>This method also works for more complex cases. Let&#8217;s add a few new entities to our model: one or more discounts can be applied to each purchased product, and each discount is linked to a sales campaign. If we need to retrieve the associated discounts and campaigns in the query results, we can write something like that:</p>
<p><pre class="brush: csharp;">
var query =
    from ord in db.Orders.Include(o =&gt; OrderDetails.Select(od =&gt; od.Discounts.Select(d =&gt; d.Campaign)))
    where ord.Date &gt;= DateTime.Today
    select ord;
</pre></p>
<p>The result is the same as if we had passed &#8220;OrderDetails.Discounts.Campaign&#8221; to the standard <code>Include</code> method. Since the nested <code>Select</code> calls impair the readability, we can also use a different expression, with the same result:</p>
<p><pre class="brush: csharp;">
var query =
    from ord in db.Orders.Include(o =&gt; o.OrderDetails
                                        .SelectMany(od =&gt; od.Discounts)
                                        .Select(d =&gt; d.Campaign))
    where ord.Date &gt;= DateTime.Today
    select ord;
</pre></p>
<p>To conclude, I just have two remarks regarding this solution:</p>
<ul>
<li>A similar extension method is included in the <a href="http://blogs.msdn.com/b/adonet/archive/2010/07/14/ctp4announcement.aspx">Entity Framework Feature CTP4</a> (see <a href="http://romiller.com/2010/07/14/ef-ctp4-tips-tricks-include-with-lambda/">this article</a> for details). So it is possible that it will eventually be included in the framework (perhaps in a service pack for .NET 4.0 ?).</li>
<li>Even though this solution targets Entity Framework 4.0, it should be possible to adapt it for EF 3.5. The <code>ExpressionVisitor</code> class is not available in 3.5, but there is another implementation of it in Joseph Albahari&#8217;s <a href="http://www.albahari.com/nutshell/linqkit.aspx">LINQKit</a>. I didn&#8217;t try it, but it should work the same way&#8230;</li>
</ul>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2ftomlev2.wordpress.com%2f2010%2f10%2f03%2fentity-framework-using-include-with-lambda-expressions%2f"><img src="http://dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://tomlev2.wordpress.com/2010/10/03/entity-framework-using-include-with-lambda-expressions/" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tomlev2.wordpress.com/316/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tomlev2.wordpress.com/316/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tomlev2.wordpress.com/316/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tomlev2.wordpress.com/316/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/tomlev2.wordpress.com/316/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/tomlev2.wordpress.com/316/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/tomlev2.wordpress.com/316/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/tomlev2.wordpress.com/316/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tomlev2.wordpress.com/316/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tomlev2.wordpress.com/316/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tomlev2.wordpress.com/316/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tomlev2.wordpress.com/316/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tomlev2.wordpress.com/316/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tomlev2.wordpress.com/316/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tomlev2.wordpress.com&amp;blog=7442815&amp;post=316&amp;subd=tomlev2&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://tomlev2.wordpress.com/2010/10/03/entity-framework-using-include-with-lambda-expressions/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f4acdb91aba11ddf8f03d4b12453f3d5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tomlev</media:title>
		</media:content>

		<media:content url="http://dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://tomlev2.wordpress.com/2010/10/03/entity-framework-using-include-with-lambda-expressions/" medium="image">
			<media:title type="html">kick it on DotNetKicks.com</media:title>
		</media:content>
	</item>
		<item>
		<title>[WPF] A simpler Grid using XAML attribute syntax</title>
		<link>http://tomlev2.wordpress.com/2010/07/20/wpf-a-simpler-grid-using-xaml-attribute-syntax/</link>
		<comments>http://tomlev2.wordpress.com/2010/07/20/wpf-a-simpler-grid-using-xaml-attribute-syntax/#comments</comments>
		<pubDate>Tue, 20 Jul 2010 20:51:10 +0000</pubDate>
		<dc:creator>Thomas Levesque</dc:creator>
				<category><![CDATA[Code sample]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[grid]]></category>
		<category><![CDATA[XAML]]></category>

		<guid isPermaLink="false">http://tomlev2.wordpress.com/?p=312</guid>
		<description><![CDATA[The Grid control is one of the most frequently used containers in WPF. It allows to layout elements easily in rows and columns. Unfortunately the code to declare it, while simple to write, is made quite awkward by the use of the property element syntax: In that example, more than half the code is made [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tomlev2.wordpress.com&amp;blog=7442815&amp;post=312&amp;subd=tomlev2&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>The <code>Grid</code> control is one of the most frequently used containers in WPF. It allows to layout elements easily in rows and columns. Unfortunately the code to declare it, while simple to write, is made quite awkward by the use of the property element syntax:</p>
<p><pre class="brush: xml;">
&lt;Grid&gt;
    &lt;Grid.RowDefinitions&gt;
        &lt;RowDefinition Height=&quot;Auto&quot;/&gt;
        &lt;RowDefinition Height=&quot;5&quot;/&gt;
        &lt;RowDefinition Height=&quot;*&quot;/&gt;
    &lt;/Grid.RowDefinitions&gt;
    &lt;Grid.ColumnDefinitions&gt;
        &lt;ColumnDefinition Width=&quot;60&quot; /&gt;
        &lt;ColumnDefinition Width=&quot;*&quot; /&gt;
    &lt;/Grid.ColumnDefinitions&gt;
    
    &lt;Label Content=&quot;Name&quot; Grid.Row=&quot;0&quot; Grid.Column=&quot;0&quot; /&gt;
    &lt;TextBox Text=&quot;Hello world&quot; Grid.Row=&quot;0&quot; Grid.Column=&quot;1&quot;/&gt;
    &lt;Rectangle Fill=&quot;Black&quot; Grid.Row=&quot;1&quot; Grid.ColumnSpan=&quot;2&quot;/&gt;
    &lt;Label Content=&quot;Image&quot; Grid.Row=&quot;2&quot; Grid.Column=&quot;0&quot; /&gt;
    &lt;Image Source=&quot;Resources/Desert.jpg&quot; Grid.Row=&quot;2&quot; Grid.Column=&quot;1&quot; /&gt;
&lt;/Grid&gt;
</pre></p>
<p>In that example, more than half the code is made of the grid definition ! Even though this syntax offers a great flexibility and a precise control of the layout, in mot cases we just need to define the height of rows and the width of columns&#8230; so it would be much simpler if we could declare the grid using the attribute syntax, as follows:</p>
<p><pre class="brush: xml;">
&lt;Grid Rows=&quot;Auto,5,*&quot; Columns=&quot;60,*&quot;&gt;
    ...
&lt;/Grid&gt;
</pre></p>
<p>This article shows how to reach that goal, by creating a <code>SimpleGrid</code> class derived from <code>Grid</code>.</p>
<p>First of all, our class needs two new properties: <code>Rows</code> and <code>Columns</code>. These properties define the heights and widths of rows and columns, respectively. These dimensions are not just numbers: values such as <code>"*"</code>, <code>"2*"</code> ou <code>"Auto"</code> are valid dimensions for grid bands. WPF has a specific type to represent these values: the <code>GridLength</code> structure. So our new properties will be collections of <code>GridLength</code> objects. Here&#8217;s the signature of the <code>SimpleGrid</code> class:</p>
<p><pre class="brush: csharp;">
public class SimpleGrid : Grid
{
    public IList&lt;GridLength&gt; Rows { get; set; }
    public IList&lt;GridLength&gt; Columns { get; set; }
}
</pre></p>
<p>Since these properties are in charge of defining the grid&#8217;s rows and columns, they have to modify the <code>RowDefinitions</code> and <code>ColumnDefinitions</code> properties of the base class. Here&#8217;s how to implement them to get the desired result :</p>
<p><pre class="brush: csharp;">
        private IList&lt;GridLength&gt; _rows;
        public IList&lt;GridLength&gt; Rows
        {
            get { return _rows; }
            set
            {
                _rows = value;
                RowDefinitions.Clear();
                if (_rows == null)
                    return;
                foreach (var length in _rows)
                {
                    RowDefinitions.Add(new RowDefinition { Height = length });
                }
            }
        }

        private IList&lt;GridLength&gt; _columns;
        public IList&lt;GridLength&gt; Columns
        {
            get { return _columns; }
            set
            {
                _columns = value;
                ColumnDefinitions.Clear();
                if (_columns == null)
                    return;
                foreach (var length in _columns)
                {
                    ColumnDefinitions.Add(new ColumnDefinition { Width = length });
                }
            }
        }
</pre></p>
<p>At this point, our <code>SimpleGrid</code> is already usable&#8230; from C# code, which doesn&#8217;t really help us since we&#8217;re trying to make the <em>XAML</em> code simpler. So we need to find a way to declare the values of these properties in XAML attributes, which isn&#8217;t obvious since they are collections&#8230;</p>
<p>In XAML, all attributes are written in the form of strings. To convert these strings to values of the required type, WPF makes use of converters, which are classes derived from <code>TypeConverter</code>, associated with each type which supports conversion to and from other types. For instance, the converter for the <code>GridLength</code> structure is the <code>GridLengthConverter</code> class, which can convert numbers and strings to <code>GridLength</code> objects, and back. The conversion mechanism is described in more detail in <a href="http://msdn.microsoft.com/en-us/library/aa970913.aspx">this MSDN article</a>.</p>
<p>So we need to create a converter and associate it to the type of the <code>Rows</code> and <code>Columns</code> properties. Since we don&#8217;t have control over the <code>IList&lt;T&gt;</code> type, we&#8217;ll start by creating a specific <code>GridLengthCollection</code> type to be used instead of <code>IList&lt;GridLength&gt;</code>, and we&#8217;ll associate a custom converter with it (<code>GridLengthCollectionConverter</code>):</p>
<p><pre class="brush: csharp;">
    [TypeConverter(typeof(GridLengthCollectionConverter))]
    public class GridLengthCollection : ReadOnlyCollection&lt;GridLength&gt;
    {
        public GridLengthCollection(IList&lt;GridLength&gt; lengths)
            : base(lengths)
        {
        }
    }
</pre></p>
<p>Why is that collection read-only ? That just because allowing to add or remove rows and columns would make the implementation more complex, and it wouldn&#8217;t bring any benefit for our objective, which is to make it easier to define a <code>Grid</code> in XAML. So, let&#8217;s keep it simple, at least for now&#8230; The <code>ReadOnlyCollection&lt;T&gt;</code> does exactly what we need, so we just inherit from it, rather than reinventing the wheel.</p>
<p>Notice the use of the <code>TypeConverter</code> attribute: that&#8217;s how we tell the framework which converter should be used with the <code>GridLengthCollection</code> type. Now, all we need to do is to implement that converter :</p>
<p><pre class="brush: csharp;">
    public class GridLengthCollectionConverter : TypeConverter
    {
        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            if (sourceType == typeof(string))
                return true;
            return base.CanConvertFrom(context, sourceType);
        }

        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
        {
            if (destinationType == typeof(string))
                return true;
            return base.CanConvertTo(context, destinationType);
        }

        public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
        {
            string s = value as string;
            if (s != null)
                return ParseString(s, culture);
            return base.ConvertFrom(context, culture, value);
        }

        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            if (destinationType == typeof(string) &amp;&amp; value is GridLengthCollection)
                return ToString((GridLengthCollection)value, culture);
            return base.ConvertTo(context, culture, value, destinationType);
        }

        private string ToString(GridLengthCollection value, CultureInfo culture)
        {
            var converter = new GridLengthConverter();
            return string.Join(&quot;,&quot;, value.Select(v =&gt; converter.ConvertToString(v)));
        }

        private GridLengthCollection ParseString(string s, CultureInfo culture)
        {
            var converter = new GridLengthConverter();
            var lengths = s.Split(',').Select(p =&gt; (GridLength)converter.ConvertFromString(p.Trim()));
            return new GridLengthCollection(lengths.ToArray());
        }
    }
</pre></p>
<p>This class can converte a <code>GridLengthCollection</code> to and from a string, in which individual dimensions are separated by commas. Notice the use of the <code>GridLengthConverter</code>: since there already is a converter for the elements of the collections, we&#8217;d better use it rather than try to reimplement the logic to parse a <code>GridLength</code>&#8230;</p>
<p>Now that all pieces are ready, we can try our new simple grid:</p>
<p><pre class="brush: xml;">
&lt;my:SimpleGrid Rows=&quot;Auto,5,*&quot; Columns=&quot;60,*&quot;&gt;
    &lt;Label Content=&quot;Name&quot; Grid.Row=&quot;0&quot; Grid.Column=&quot;0&quot; /&gt;
    &lt;TextBox Text=&quot;Hello world&quot; Grid.Row=&quot;0&quot; Grid.Column=&quot;1&quot;/&gt;
    &lt;Rectangle Fill=&quot;Black&quot; Grid.Row=&quot;1&quot; Grid.ColumnSpan=&quot;2&quot;/&gt;
    &lt;Label Content=&quot;Image&quot; Grid.Row=&quot;2&quot; Grid.Column=&quot;0&quot; /&gt;
    &lt;Image Source=&quot;Resources/Desert.jpg&quot; Grid.Row=&quot;2&quot; Grid.Column=&quot;1&quot; /&gt;
&lt;/my:SimpleGrid&gt;
</pre></p>
<p>We end up with a much shorter and more readable code than with a normal <code>Grid</code>, and the result is the same: mission complete <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Of course, we could improve this class in a number of ways: implement <code>Rows</code> and <code>Columns</code> as dependency properties in order to allow binding, handle addition and removal of rows and columns&#8230; However, this grid is intended for very simple scenarios, where the grid is defined once and for all, and is not modified at runtime (which is presumably the most frequent use case), so it seems sensible to keep it as simple as possible. For more specific needs, like specifying a minimum/maximum width or a shared sized group, we&#8217;ll stick to the standard <code>Grid</code>.</p>
<p>For reference, here&#8217;s the final code of the <code>SimpleGrid</code> class:</p>
<p><pre class="brush: csharp;">
    public class SimpleGrid : Grid
    {
        private GridLengthCollection _rows;
        public GridLengthCollection Rows
        {
            get { return _rows; }
            set
            {
                _rows = value;
                RowDefinitions.Clear();
                if (_rows == null)
                    return;
                foreach (var length in _rows)
                {
                    RowDefinitions.Add(new RowDefinition { Height = length });
                }
            }
        }

        private GridLengthCollection _columns;
        public GridLengthCollection Columns
        {
            get { return _columns; }
            set
            {
                _columns = value;
                if (_columns == null)
                    return;
                ColumnDefinitions.Clear();
                foreach (var length in _columns)
                {
                    ColumnDefinitions.Add(new ColumnDefinition { Width = length });
                }
            }
        }
    }
</pre></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tomlev2.wordpress.com/312/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tomlev2.wordpress.com/312/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tomlev2.wordpress.com/312/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tomlev2.wordpress.com/312/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/tomlev2.wordpress.com/312/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/tomlev2.wordpress.com/312/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/tomlev2.wordpress.com/312/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/tomlev2.wordpress.com/312/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tomlev2.wordpress.com/312/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tomlev2.wordpress.com/312/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tomlev2.wordpress.com/312/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tomlev2.wordpress.com/312/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tomlev2.wordpress.com/312/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tomlev2.wordpress.com/312/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tomlev2.wordpress.com&amp;blog=7442815&amp;post=312&amp;subd=tomlev2&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://tomlev2.wordpress.com/2010/07/20/wpf-a-simpler-grid-using-xaml-attribute-syntax/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f4acdb91aba11ddf8f03d4b12453f3d5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tomlev</media:title>
		</media:content>
	</item>
		<item>
		<title>[C#] A simple implementation of the WeakEvent pattern</title>
		<link>http://tomlev2.wordpress.com/2010/05/17/c-a-simple-implementation-of-the-weakevent-pattern/</link>
		<comments>http://tomlev2.wordpress.com/2010/05/17/c-a-simple-implementation-of-the-weakevent-pattern/#comments</comments>
		<pubDate>Mon, 17 May 2010 21:12:36 +0000</pubDate>
		<dc:creator>Thomas Levesque</dc:creator>
				<category><![CDATA[Code sample]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[code snippet]]></category>
		<category><![CDATA[weak event]]></category>

		<guid isPermaLink="false">http://tomlev2.wordpress.com/?p=306</guid>
		<description><![CDATA[As you probably know, incorrect usage of events is one of the main causes for memory leaks in .NET applications : an event keeps references to its listener objects (through a delegate), which prevents the garbage collector from collecting them when they&#8217;re not used anymore. This is especially true of static events, because the references [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tomlev2.wordpress.com&amp;blog=7442815&amp;post=306&amp;subd=tomlev2&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>As you probably know, incorrect usage of events is one of the main causes for memory leaks in .NET applications : an event keeps references to its listener objects (through a delegate), which prevents the garbage collector from collecting them when they&#8217;re not used anymore. This is especially true of static events, because the references are kept for all the lifetime of the application. If the application often adds handlers to the event and never removes them, the memory usage will grow as long as the application runs, until no more memory is available.</p>
<p>The &#8220;obvious&#8221; solution, of course, is to unsubscribe from the event when you&#8217;re done with it. Unfortunately, it&#8217;s not always obvious to know <em>when</em> you can unsubscribe&#8230; an object that goes out of scope usually isn&#8217;t aware of it, so it doesn&#8217;t have a chance to unsubscribe from the event.</p>
<p>Another approach is to implement the <a href="http://msdn.microsoft.com/en-us/library/aa970850.aspx">WeakEvent pattern</a>, which principle is to keep only weak references to the listeners. That way, unsubscribed listeners can be claimed by the garbage collector. Microsoft included in WPF a few types to deal with the WeakEvent pattern (<code>WeakEventManager</code> class and <code>IWeakEventListener</code> interface), and gives guidelines on how to implement your own weak event. However this technique is not very convenient, because you need to create dedicated classes to expose new events, and the listeners need to implement a specific interface.</p>
<p>So I thought about another implementation, which allows creating weak events almost the same way as normal events. My first idea was to use a list of <code>WeakReference</code>s to store the list of subscribed delegates. But this doesn&#8217;t work so well, because of the way we typically use delegates :</p>
<p><pre class="brush: csharp;">
myObject.MyEvent += new EventHandler(myObject_MyEvent);
</pre></p>
<p>We create a delegate, subscribe it to the event, and&#8230; drop it. So the only accessible reference to the delegate is actually a weak reference, so there&#8217;s nothing to prevent its garbage collection&#8230; and that&#8217;s exactly what happens ! After a variable period of time (from my observations, no more than a few seconds), the delegate is garbage collected, and isn&#8217;t called anymore when the event is raised.</p>
<p>Rather than keeping a weak reference to the delegate itself, we should use a less transient object : the target object of the delegate (<code>Delegate.Target</code>) would be a better choice. So I created the <code>WeakDelegate&lt;TDelegate&gt;</code> class, which wraps a delegate by storing separately the method and a weak reference to the target :</p>
<p><pre class="brush: csharp; collapse: true; light: false; toolbar: true;">
    public class WeakDelegate&lt;TDelegate&gt; : IEquatable&lt;TDelegate&gt;
    {
        private WeakReference _targetReference;
        private MethodInfo _method;

        public WeakDelegate(Delegate realDelegate)
        {
            if (realDelegate.Target != null)
                _targetReference = new WeakReference(realDelegate.Target);
            else
                _targetReference = null;
            _method = realDelegate.Method;
        }

        public TDelegate GetDelegate()
        {
            return (TDelegate)(object)GetDelegateInternal();
        }

        private Delegate GetDelegateInternal()
        {
            if (_targetReference != null)
            {
                return Delegate.CreateDelegate(typeof(TDelegate), _targetReference.Target, _method);
            }
            else
            {
                return Delegate.CreateDelegate(typeof(TDelegate), _method);
            }
        }

        public bool IsAlive
        {
            get { return _targetReference == null || _targetReference.IsAlive; }
        }


        #region IEquatable&lt;TDelegate&gt; Members

        public bool Equals(TDelegate other)
        {
            Delegate d = (Delegate)(object)other;
            return d != null
                &amp;&amp; d.Target == _targetReference.Target
                &amp;&amp; d.Method.Equals(_method);
        }

        #endregion

        internal void Invoke(params object[] args)
        {
            Delegate handler = (Delegate)(object)GetDelegateInternal();
            handler.DynamicInvoke(args);
        }
    }
</pre></p>
<p>Now, we just need to manage a list of these <code>WeakDelegate&lt;TDelegate&gt;</code>. This is done by the <code>WeakEvent&lt;TDelegate&gt;</code> class :</p>
<p><pre class="brush: csharp; collapse: true; light: false; toolbar: true;">
    public class WeakEvent&lt;TEventHandler&gt;
    {
        private List&lt;WeakDelegate&lt;TEventHandler&gt;&gt; _handlers;

        public WeakEvent()
        {
            _handlers = new List&lt;WeakDelegate&lt;TEventHandler&gt;&gt;();
        }

        public virtual void AddHandler(TEventHandler handler)
        {
            Delegate d = (Delegate)(object)handler;
            _handlers.Add(new WeakDelegate&lt;TEventHandler&gt;(d));
        }

        public virtual void RemoveHandler(TEventHandler handler)
        {
            // also remove &quot;dead&quot; (garbage collected) handlers
            _handlers.RemoveAll(wd =&gt; !wd.IsAlive || wd.Equals(handler));
        }

        public virtual void Raise(object sender, EventArgs e)
        {
            var handlers = _handlers.ToArray();
            foreach (var weakDelegate in handlers)
            {
                if (weakDelegate.IsAlive)
                {
                    weakDelegate.Invoke(sender, e);
                }
                else
                {
                    _handlers.Remove(weakDelegate);
                }
            }
        }

        protected List&lt;WeakDelegate&lt;TEventHandler&gt;&gt; Handlers
        {
            get { return _handlers; }
        }
    }
</pre></p>
<p>This class automatically handles the removal of &#8220;dead&#8221; (garbage collected) handlers, and provides a <code>Raise</code> method to call the handlers. It can be used as follows :</p>
<p><pre class="brush: csharp;">
        private WeakEvent&lt;EventHandler&gt; _myEvent = new WeakEvent&lt;EventHandler&gt;();
        public event EventHandler MyEvent
        {
            add { _myEvent.AddHandler(value); }
            remove { _myEvent.RemoveHandler(value); }
        }

        protected virtual void OnMyEvent()
        {
            _myEvent.Raise(this, EventArgs.Empty);
        }
</pre></p>
<p>This is a bit longer to write than a &#8220;regular&#8221; event, but considering the benefits, it&#8217;s very acceptable. Anyway, you can easily create a Visual Studio snippet to quickly create a weak event, with only 3 fields to fill in :</p>
<p><pre class="brush: xml; collapse: true; light: false; toolbar: true;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; ?&gt;
&lt;CodeSnippets  xmlns=&quot;http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet&quot;&gt;
  &lt;CodeSnippet Format=&quot;1.0.0&quot;&gt;
    &lt;Header&gt;
      &lt;Title&gt;wevt&lt;/Title&gt;
      &lt;Shortcut&gt;wevt&lt;/Shortcut&gt;
      &lt;Description&gt;Code snippet for a weak event&lt;/Description&gt;
      &lt;Author&gt;Thomas Levesque&lt;/Author&gt;
      &lt;SnippetTypes&gt;
        &lt;SnippetType&gt;Expansion&lt;/SnippetType&gt;
      &lt;/SnippetTypes&gt;
    &lt;/Header&gt;
    &lt;Snippet&gt;
      &lt;Declarations&gt;
        &lt;Literal&gt;
          &lt;ID&gt;type&lt;/ID&gt;
          &lt;ToolTip&gt;Event type&lt;/ToolTip&gt;
          &lt;Default&gt;EventHandler&lt;/Default&gt;
        &lt;/Literal&gt;
        &lt;Literal&gt;
          &lt;ID&gt;event&lt;/ID&gt;
          &lt;ToolTip&gt;Event name&lt;/ToolTip&gt;
          &lt;Default&gt;MyEvent&lt;/Default&gt;
        &lt;/Literal&gt;
        &lt;Literal&gt;
          &lt;ID&gt;field&lt;/ID&gt;
          &lt;ToolTip&gt;Name of the field holding the registered handlers&lt;/ToolTip&gt;
          &lt;Default&gt;_myEvent&lt;/Default&gt;
        &lt;/Literal&gt;
      &lt;/Declarations&gt;
      &lt;Code Language=&quot;csharp&quot;&gt;
        &lt;![CDATA[private WeakEvent&lt;$type$&gt; $field$ = new WeakEvent&lt;EventHandler&gt;();
        public event $type$ $event$
        {
            add { $field$.AddHandler(value); }
            remove { $field$.RemoveHandler(value); }
        }

        protected virtual void On$event$()
        {
            $field$.Raise(this, EventArgs.Empty);
        }
	$end$]]&gt;
      &lt;/Code&gt;
    &lt;/Snippet&gt;
  &lt;/CodeSnippet&gt;
&lt;/CodeSnippets&gt;
</pre></p>
<p>This snippet gives the following result in Visual Studio :</p>
<p><a href="http://tomlev.files.wordpress.com/2010/05/screenshot_snippet_wevt.png"><img src="http://tomlev.files.wordpress.com/2010/05/screenshot_snippet_wevt.png?w=780" alt="Code snippet pour implémenter un WeakEvent" title="Code snippet pour implémenter un WeakEvent"   class="aligncenter size-full wp-image-343" /></a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tomlev2.wordpress.com/306/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tomlev2.wordpress.com/306/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tomlev2.wordpress.com/306/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tomlev2.wordpress.com/306/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/tomlev2.wordpress.com/306/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/tomlev2.wordpress.com/306/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/tomlev2.wordpress.com/306/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/tomlev2.wordpress.com/306/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tomlev2.wordpress.com/306/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tomlev2.wordpress.com/306/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tomlev2.wordpress.com/306/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tomlev2.wordpress.com/306/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tomlev2.wordpress.com/306/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tomlev2.wordpress.com/306/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tomlev2.wordpress.com&amp;blog=7442815&amp;post=306&amp;subd=tomlev2&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://tomlev2.wordpress.com/2010/05/17/c-a-simple-implementation-of-the-weakevent-pattern/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f4acdb91aba11ddf8f03d4b12453f3d5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tomlev</media:title>
		</media:content>

		<media:content url="http://tomlev.files.wordpress.com/2010/05/screenshot_snippet_wevt.png" medium="image">
			<media:title type="html">Code snippet pour implémenter un WeakEvent</media:title>
		</media:content>
	</item>
		<item>
		<title>Automating null checks with Linq expressions</title>
		<link>http://tomlev2.wordpress.com/2010/02/21/automating-null-checks-with-linq-expressions/</link>
		<comments>http://tomlev2.wordpress.com/2010/02/21/automating-null-checks-with-linq-expressions/#comments</comments>
		<pubDate>Sun, 21 Feb 2010 20:42:58 +0000</pubDate>
		<dc:creator>Thomas Levesque</dc:creator>
				<category><![CDATA[Code sample]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[expression]]></category>
		<category><![CDATA[linq]]></category>
		<category><![CDATA[null check]]></category>
		<category><![CDATA[proof of concept]]></category>

		<guid isPermaLink="false">http://tomlev2.wordpress.com/?p=244</guid>
		<description><![CDATA[The problem Have you ever written code like the following ? I bet you have ! You just need to get the value of xx.Foo.Bar.Baz.Name, but you have to test every intermediate object to ensure that it&#8217;s not null. It can quickly become annoying if the property you need is nested in a deep object [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tomlev2.wordpress.com&amp;blog=7442815&amp;post=244&amp;subd=tomlev2&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><strong>The problem</strong></p>
<p>Have you ever written code like the following ?</p>
<p><pre class="brush: csharp;">
X xx = GetX();
string name = &quot;Default&quot;;
if (xx != null &amp;&amp; xx.Foo != null &amp;&amp; xx.Foo.Bar != null &amp;&amp; xx.Foo.Bar.Baz != null)
{
    name = xx.Foo.Bar.Baz.Name;
}
</pre></p>
<p>I bet you have ! You just need to get the value of <code>xx.Foo.Bar.Baz.Name</code>, but you have to test <em>every</em> intermediate object to ensure that it&#8217;s not null. It can quickly become annoying if the property you need is nested in a deep object graph&#8230;.</p>
<p><strong>A solution</strong></p>
<p>Linq offers a very interesting feature which can help solve that problem : expressions. C# 3.0 makes it possible to retrieve the abstract syntax tree (AST) of a lambda expression, and perform all kinds of manipulations on it. It is also possible to dynamically generate an AST, compile it to obtain a delegate, and execute it.</p>
<p>How is this related to the problem described above ? Well, Linq makes it possible to analyse the AST for the expression that accesses the <code>xx.Foo.Bar.Baz.Name</code> property, and rewrite that AST to insert null checks where needed. So we&#8217;re going to create a <code>NullSafeEval</code> extension method, which takes as a parameter the lambda expression defining how to access a property, and the default value to return if a null object is encountered along the way.</p>
<p>That method will transform the expression <code>xx.Foo.Bar.Baz.Name</code> into that :</p>
<p><pre class="brush: csharp;">
    (xx == null)
    ? defaultValue
    : (xx.Foo == null)
      ? defaultValue
      : (xx.Foo.Bar == null)
        ? defaultValue
        : (xx.Foo.Bar.Baz == null)
          ? defaultValue
          : xx.Foo.Bar.Baz.Name;
</pre></p>
<p>Here&#8217;s the implementation of the <code>NullSafeEval</code> method :</p>
<p><pre class="brush: csharp; collapse: true; light: false; toolbar: true;">
        public static TResult NullSafeEval&lt;TSource, TResult&gt;(this TSource source, Expression&lt;Func&lt;TSource, TResult&gt;&gt; expression, TResult defaultValue)
        {
            var safeExp = Expression.Lambda&lt;Func&lt;TSource, TResult&gt;&gt;(
                NullSafeEvalWrapper(expression.Body, Expression.Constant(defaultValue)),
                expression.Parameters[0]);

            var safeDelegate = safeExp.Compile();
            return safeDelegate(source);
        }

        private static Expression NullSafeEvalWrapper(Expression expr, Expression defaultValue)
        {
            Expression obj;
            Expression safe = expr;

            while (!IsNullSafe(expr, out obj))
            {
                var isNull = Expression.Equal(obj, Expression.Constant(null));

                safe =
                    Expression.Condition
                    (
                        isNull,
                        defaultValue,
                        safe
                    );

                expr = obj;
            }
            return safe;
        }

        private static bool IsNullSafe(Expression expr, out Expression nullableObject)
        {
            nullableObject = null;

            if (expr is MemberExpression || expr is MethodCallExpression)
            {
                Expression obj;
                MemberExpression memberExpr = expr as MemberExpression;
                MethodCallExpression callExpr = expr as MethodCallExpression;

                if (memberExpr != null)
                {
                    // Static fields don't require an instance
                    FieldInfo field = memberExpr.Member as FieldInfo;
                    if (field != null &amp;&amp; field.IsStatic)
                        return true;

                    // Static properties don't require an instance
                    PropertyInfo property = memberExpr.Member as PropertyInfo;
                    if (property != null)
                    {
                        MethodInfo getter = property.GetGetMethod();
                        if (getter != null &amp;&amp; getter.IsStatic)
                            return true;
                    }
                    obj = memberExpr.Expression;
                }
                else
                {
                    // Static methods don't require an instance
                    if (callExpr.Method.IsStatic)
                        return true;

                    obj = callExpr.Object;
                }

                // Value types can't be null
                if (obj.Type.IsValueType)
                    return true;

                // Instance member access or instance method call is not safe
                nullableObject = obj;
                return false;
            }
            return true;
        }
</pre></p>
<p>In short, this code walks up the lambda expression tree, and surrounds each property access or instance method call with a conditional expression <em>(condition ? value if true : value if false)</em>.</p>
<p>And here&#8217;s how we can use this method :</p>
<p><pre class="brush: csharp;">
string name = xx.NullSafeEval(x =&gt; x.Foo.Bar.Baz.Name, &quot;Default&quot;);
</pre></p>
<p>Much clearer and concise than our initial code, isn&#8217;t it ? <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Note that the proposed implementation handles  not only properties, but also method calls, so we could write something like that :</p>
<p><pre class="brush: csharp;">
string name = xx.NullSafeEval(x =&gt; x.Foo.GetBar(42).Baz.Name, &quot;Default&quot;);
</pre></p>
<p>Indexers are not handled yet, but they could be added quite easily ; I will leave it to you to do it if you have the use for it <img src='http://s1.wp.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p><strong>Limitations</strong></p>
<p>Even though that solution can seem very interesting at first sight, please read what follows before you integrate this code into a real world program&#8230;</p>
<ul>
<li>First, the proposed code is just a proof of concept, and as such, hasn&#8217;t been thoroughly tested, so it&#8217;s probably not very reliable.</li>
<li>Secondly, keep in mind that dynamic code generation from an expression tree is tough work for the CLR, and will have a big impact on performance. A quick test shows that using the <code>NullSafeEval</code> method is about 10000 times slower than accessing the property directly&#8230;
<p>A possible approach to limit that issue would be to cache the delegates generated for each expression, to avoid regenerating them every time. Unfortunately, as far as I know there is no simple and reliable way to compare two Linq expressions, which makes it much harder to implement such a cache.</li>
<li>Last, you might have noticed that intermediate properties and methods are evaluated several times ; not only this is bad for performance, but more importantly, it could have side effects that are hard to predict, depending on how the properties and methods are implemented.
<p>A possible workaround would be to rewrite the conditional expression as follows :</p>
<p><pre class="brush: csharp;">
Foo foo = null;
Bar bar = null;
Baz baz = null;
var name =
    (x == null)
    ? defaultValue
    : ((foo = x.Foo) == null)
      ? defaultValue
      : ((bar = foo.Bar) == null)
        ? defaultValue
        : ((baz = bar.Baz) == null)
          ? defaultValue
          : baz.Name;
</pre></p>
<p>Unfortunately, this is not possible in .NET 3.5 : that version only supports simple expressions, so it&#8217;s not possible to declare variables, assign values to them, or write several distinct instructions. However, in .NET 4.0, support for Linq expressions has been largely improved, and makes it possible to generate that kind of code. I&#8217;m currently trying to improve the <code>NullSafeEval</code> method to take advantage of the new .NET 4.0 features, but it turns out to be much more difficult than I had anticipated&#8230; If I manage to work it out, I&#8217;ll let you know and post the code !</li>
</ul>
<p>To conclude, I wouldn&#8217;t recommend using that technique in real programs, at least not in its current state. However, it gives an interesting insight on the possibilities offered by Linq expressions. If you&#8217;re new to this, you should know that Linq expressions are used (among other things) :</p>
<ul>
<li>To generate SQL queries in ORMs like Linq to SQL or Entity Framework</li>
<li>To build complex predicates dynamically, like in the <a href="http://www.albahari.com/nutshell/predicatebuilder.aspx">PredicateBuilder</a> class by Joseph Albahari</li>
<li>To implement &#8220;static reflection&#8221;, which has generated <a href="http://www.google.com/search?tbo=1&amp;tbs=blg:1&amp;q=static+reflection">a lot of buzz on technical blogs</a> lately</li>
</ul>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tomlev2.wordpress.com/244/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tomlev2.wordpress.com/244/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tomlev2.wordpress.com/244/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tomlev2.wordpress.com/244/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/tomlev2.wordpress.com/244/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/tomlev2.wordpress.com/244/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/tomlev2.wordpress.com/244/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/tomlev2.wordpress.com/244/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tomlev2.wordpress.com/244/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tomlev2.wordpress.com/244/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tomlev2.wordpress.com/244/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tomlev2.wordpress.com/244/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tomlev2.wordpress.com/244/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tomlev2.wordpress.com/244/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tomlev2.wordpress.com&amp;blog=7442815&amp;post=244&amp;subd=tomlev2&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://tomlev2.wordpress.com/2010/02/21/automating-null-checks-with-linq-expressions/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f4acdb91aba11ddf8f03d4b12453f3d5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tomlev</media:title>
		</media:content>
	</item>
		<item>
		<title>[VS2010] Binding support in InputBindings</title>
		<link>http://tomlev2.wordpress.com/2009/10/26/vs2010-binding-support-in-inputbindings/</link>
		<comments>http://tomlev2.wordpress.com/2009/10/26/vs2010-binding-support-in-inputbindings/#comments</comments>
		<pubDate>Mon, 26 Oct 2009 15:30:25 +0000</pubDate>
		<dc:creator>Thomas Levesque</dc:creator>
				<category><![CDATA[WPF]]></category>
		<category><![CDATA[.NET 4.0]]></category>
		<category><![CDATA[binding]]></category>
		<category><![CDATA[InputBinding]]></category>
		<category><![CDATA[KeyBinding]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[Visual Studio 2010]]></category>
		<category><![CDATA[WPF 4.0]]></category>
		<category><![CDATA[XAML]]></category>

		<guid isPermaLink="false">http://tomlev2.wordpress.com/?p=240</guid>
		<description><![CDATA[THE feature that was missing from WPF ! Visual Studio 2010 beta 2 has been released last week, and it brings to WPF a long awaited feature : support for bindings in InputBindings. As a reminder, the issue in previous releases was that the Command property of the InputBinding class wasn&#8217;t a DependencyProperty, so it [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tomlev2.wordpress.com&amp;blog=7442815&amp;post=240&amp;subd=tomlev2&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><strong>THE feature that was missing from WPF !</strong></p>
<p>Visual Studio 2010 beta 2 has been released last week, and it brings to WPF a long awaited feature : support for bindings in <code>InputBindings</code>.</p>
<p>As a reminder, the issue in previous releases was that the <code>Command</code> property of the <code>InputBinding</code> class wasn&#8217;t a <code>DependencyProperty</code>, so it wasn&#8217;t possible to bind it. Furthermore, <code>InputBindings</code> didn&#8217;t inherit the parent DataContext, which made it difficult to provide alternative implementations&#8230;</p>
<p>Until now, in order to bind the <code>Command</code> of a <code>KeyBinding</code> or <code>MouseBinding</code> to a property of the <code>DataContext</code>, we had to resort to clumsy workarounds&#8230; I had eventually came up with an acceptable solution, described in <a href="http://tomlev2.wordpress.com/2009/03/17/wpf-using-inputbindings-with-the-mvvm-pattern/">this post</a>, but I wasn&#8217;t really satisfied with it (it used reflection on private members, and had annoying limitations).</p>
<p>More recently, I found a better solution in the <a href="http://www.codeplex.com/wpf/Release/ProjectReleases.aspx?ReleaseId=14962">MVVM toolkit</a> : a <code>CommandReference</code> class, inherited from <code>Freezable</code>, allows to put a reference to a ViewModel command in the page or control resources, so that it can be used later with <code>StaticResource</code>. It&#8217;s much cleaner than my previous solution, but still not very straightforward&#8230;</p>
<p>WPF 4.0 solves that problem once and for all : the <code>InputBinding</code> class now inherits from <code>Freezable</code>, which allows it to inherit the <code>DataContext</code>, and the <code>Command</code>, <code>CommandParameter</code> and <code>CommandTarget</code> properties are now dependency properties. So, at last, we can forget about the clumsy workarounds described above, and go straight to the point :</p>
<p><pre class="brush: xml;">
    &lt;Window.InputBindings&gt;
        &lt;KeyBinding Key=&quot;F5&quot;
                    Command=&quot;{Binding RefreshCommand}&quot; /&gt;
    &lt;/Window.InputBindings&gt;
</pre></p>
<p>This new feature should make it much easier to develop MVVM applications !</p>
<p><strong>Help 3</strong></p>
<p>Other than that, I would like to say a few words about the new offline help system that comes with Visual Studio 2010, called &#8220;Help 3&#8243;. It&#8217;s quite a big change compared to previous versions&#8230; First, it&#8217;s not a standalone application anymore, but a locally hosted web application, so you can access the documentation with your favorite web browser. On the whole, it&#8217;s better than the previous system&#8230; much faster and more responsive than the old Document Explorer included in previous Visual Studio releases.</p>
<p>However, the new system misses the feature that was the most useful to me : the index ! Now there&#8217;s only the hierarchical view, and a search textbox. IMHO, the index was the most convenient way of looking up something in the doc, it made it very easy to access a class or member directly, even without knowing its namespace&#8230; why on earth did they remove it ? Worse still : the search results don&#8217;t show the namespace, only the class or member name. For instance, if you search &#8220;button class&#8221;, in the results there is no way to see the difference between <code>System.Windows.Forms.Button</code>, <code>System.Windows.Controls.Button</code> and <code>System.Web.UI.WebControls</code> ! You have to click each link and see where it leads&#8230; In Document Explorer, the Index Results pane showed this information clearly.</p>
<p>So, eventually I have mixed feelings about this new help system, because I will have to change the way I use the documentation. But except for this annoying detail,  I must concede that it&#8217;s objectively a big improvement over the old system&#8230;</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tomlev2.wordpress.com/240/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tomlev2.wordpress.com/240/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tomlev2.wordpress.com/240/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tomlev2.wordpress.com/240/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/tomlev2.wordpress.com/240/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/tomlev2.wordpress.com/240/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/tomlev2.wordpress.com/240/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/tomlev2.wordpress.com/240/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tomlev2.wordpress.com/240/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tomlev2.wordpress.com/240/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tomlev2.wordpress.com/240/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tomlev2.wordpress.com/240/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tomlev2.wordpress.com/240/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tomlev2.wordpress.com/240/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tomlev2.wordpress.com&amp;blog=7442815&amp;post=240&amp;subd=tomlev2&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://tomlev2.wordpress.com/2009/10/26/vs2010-binding-support-in-inputbindings/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f4acdb91aba11ddf8f03d4b12453f3d5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tomlev</media:title>
		</media:content>
	</item>
		<item>
		<title>[C# 4.0] Implementing a custom dynamic object</title>
		<link>http://tomlev2.wordpress.com/2009/10/08/c-4-0-implementing-a-custom-dynamic-object/</link>
		<comments>http://tomlev2.wordpress.com/2009/10/08/c-4-0-implementing-a-custom-dynamic-object/#comments</comments>
		<pubDate>Thu, 08 Oct 2009 00:32:07 +0000</pubDate>
		<dc:creator>Thomas Levesque</dc:creator>
				<category><![CDATA[C# 4.0]]></category>
		<category><![CDATA[Code sample]]></category>
		<category><![CDATA[.NET 4.0]]></category>
		<category><![CDATA[DLR]]></category>
		<category><![CDATA[dynamic]]></category>

		<guid isPermaLink="false">http://tomlev2.wordpress.com/?p=237</guid>
		<description><![CDATA[If you&#8217;ve been following the news about .NET, you probably know that the upcoming version 4.0 of C# introduces a new dynamic type. This type allows to access members of an object which are not statically known (at compile time). These members will be resolved at runtime, thanks to the DLR (Dynamic Language Runtime). This [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tomlev2.wordpress.com&amp;blog=7442815&amp;post=237&amp;subd=tomlev2&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;ve been following the news about .NET, you probably know that the upcoming version 4.0 of C# introduces a new <code>dynamic</code> type. This type allows to access members of an object which are not statically known (at compile time). These members will be resolved at runtime, thanks to the DLR (Dynamic Language Runtime). This feature makes it easier to manipulate COM objects, or any object which type is not statically known. You can find more information about the <code>dynamic</code> type <a href="http://msdn.microsoft.com/en-us/library/dd264736%28VS.100%29.aspx">on MSDN</a>.</p>
<p>While playing with Visual Studio 2010 beta, I realized this <code>dynamic</code> type enabled very interesting scenarios&#8230; It is indeed possible to create your own dynamic objects, with the ability to control the resolution of dynamic members. To do that, you need to implement the <a href="http://msdn.microsoft.com/en-us/library/system.dynamic.idynamicmetaobjectprovider(VS.100).aspx"><code>IDynamicMetaObjectProvider</code></a> interface. This interface seems pretty simple at first sight, since it only defines one member: the <code>GetMetaObject</code> method. But it actually gets trickier when you try to implement this method : you have to build a <code>DynamicMetaObject</code> from an <code>Expression</code>, which is far from trivial&#8230; I must admit I almost gave up when I saw the complexity of the task.</p>
<p>Fortunately, there is a much easier way to create your own dynamic objects: you just have to inherit from the <code><a href="http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicmetaobject(VS.100).aspx">DynamicObject</a></code> class, which provides a basic implementation of <code>IDynamicMetaObjectProvider</code>, and override a few methods to achieve the desired behavior.</p>
<p>Here&#8217;s a simple example, inspired from the Javascript language. In Javascript, it is possible to dynamically add members (properties or methods) to an existing type, as in the following sample:</p>
<p><pre class="brush: jscript;">
var x = new Object();
x.Message = &quot;Hello world !&quot;;
x.ShowMessage = function()
{
  alert(this.Message);
};
x.ShowMessage();
</pre></p>
<p>This code creates an object, add a <code>Message</code> property to that object by defining its value, and also adds a <code>ShowMessage</code> method to display the message.</p>
<p>In previous versions of C#, it would have been impossible to do such a thing: indeed C# is a statically typed language, which implies that members are resolved at compile time, not at runtime. Since the <code>Object</code> class doesn&#8217;t have a <code>Message</code> property or a <code>ShowMessage</code> method, the compiler won&#8217;t accept things like <code>x.Message</code> or <code>x.ShowMessage()</code>. This is where the <code>dynamic</code> type comes to the rescue, since it doesn&#8217;t resolve the members at compile time&#8230;</p>
<p>Now let&#8217;s try to create a dynamic object that allows to write a C# code similar to the Javascript code above. To do that, we will store the values of dynamic properties in a <code>Dictionary&lt;string, object&gt;</code>. To make this class work, we need to override the <a href="http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.trygetmember%28VS.100%29.aspx"><code>TryGetMember</code></a> and <a href="http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.trygetmember%28VS.100%29.aspx"><code>TrySetMember</code></a> methods. These methods implement the logic to read or write a member of the dynamic object. To illustrate the idea, let&#8217;s have a look at the code, I&#8217;ll comment it later:</p>
<p><pre class="brush: csharp;">
public class MyDynamicObject : DynamicObject
{
    private Dictionary&lt;string, object&gt; _properties = new Dictionary&lt;string, object&gt;();

    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        return _properties.TryGetValue(binder.Name, out result);
    }

    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        _properties[binder.Name] = value;
        return true;
    }
}
</pre></p>
<p>Now let&#8217;s explain the code above. The <code>TryGetMember</code> tries to find the requested property in the dictionary. Note that the name of the property is exposed as the <code>Name</code> property of the <code>binder</code> parameter. If the property exists, its value is returned in the <code>result</code> output parameter, and the method returns <code>true</code>. Otherwise, the method returns <code>false</code>, which will cause a <code>RuntimeBinderException</code> at the call site. This exception simply means that the dynamic resolution of the property failed.</p>
<p>The <code>TrySetMember</code> method performs the opposite task: it defines the value of a property. If the member doesn&#8217;t exist, it is added to the dictionary, so the method always returns <code>true</code>.</p>
<p>The following sample shows how to use this object:</p>
<p><pre class="brush: csharp;">
dynamic x = new MyDynamicObject();
x.Message = &quot;Hello world !&quot;;
Console.WriteLine(x.Message);
</pre></p>
<p>This code compiles and runs fine, and prints &#8220;Hello world !&#8221; to the console&#8230; easy, isn&#8217;t it ?</p>
<p>But what about methods ? Well, I could tell you that you need to override the <code><a href="http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.tryinvokemember%28VS.100%29.aspx">TryInvokeMember</a></code> method, which is used to handle dynamic method calls&#8230; but actually it&#8217;s not even necessary ! Our implementation already handles this feature: we just need to assign a delegate to a property of the object. It won&#8217;t actually be a real member method, just a property returning a delegate, but since the syntax to call it will be the same as a method call, it will do fine for now. Here&#8217;s an example of adding a method to the object:</p>
<p><pre class="brush: csharp;">
dynamic x = new MyDynamicObject();
x.Message = &quot;Hello world !&quot;;
x.ShowMessage = new Action(
    () =&gt;
    {
        Console.WriteLine(x.Message);
    });
x.ShowMessage();
</pre></p>
<p>Eventually, we end up with something very close to the Javascript we were trying to imitate, all with a class of less than 10 lines of code (not counting the braces)&#8230;</p>
<p>This class can be quite handy to use as an general purpose object, for instance to group some data together without having to create a specific class. In that aspect, it&#8217;s similar to an anonymous type (already existing in C# 3), but with the benefit that it can be used as a method return value, which is not possible with an anonymous type.</p>
<p>Of course there are many more useful things to do with a custom dynamic object&#8230; for instance, here&#8217;s a simple wrapper for a <code>DataRow</code>, to make it easier to access the fields:</p>
<p><pre class="brush: csharp;">
public class DynamicDataRow : DynamicObject
{
    private DataRow _dataRow;

    public DynamicDataRow(DataRow dataRow)
    {
        if (dataRow == null)
            throw new ArgumentNullException(&quot;dataRow&quot;);
        this._dataRow = dataRow;
    }

    public DataRow DataRow
    {
        get { return _dataRow; }
    }

    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        result = null;
        if (_dataRow.Table.Columns.Contains(binder.Name))
        {
            result = _dataRow[binder.Name];
            return true;
        }
        return false;
    }

    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        if (_dataRow.Table.Columns.Contains(binder.Name))
        {
            _dataRow[binder.Name] = value;
            return true;
        }
        return false;
    }
}
</pre></p>
<p>Let&#8217;s add a helper extension method to get the wrapper for a row:</p>
<p><pre class="brush: csharp;">
public static class DynamicDataRowExtensions
{
    public static dynamic AsDynamic(this DataRow dataRow)
    {
        return new DynamicDataRow(dataRow);
    }
}
</pre></p>
<p>We can now write things like that:</p>
<p><pre class="brush: csharp;">
DataTable table = new DataTable();
table.Columns.Add(&quot;FirstName&quot;, typeof(string));
table.Columns.Add(&quot;LastName&quot;, typeof(string));
table.Columns.Add(&quot;DateOfBirth&quot;, typeof(DateTime));

dynamic row = table.NewRow().AsDynamic();
row.FirstName = &quot;John&quot;;
row.LastName = &quot;Doe&quot;;
row.DateOfBirth = new DateTime(1981, 9, 12);
table.Rows.Add(row.DataRow);

// Add more rows...
// ...

var bornInThe20thCentury = from r in table.AsEnumerable()
                           let dr = r.AsDynamic()
                           where dr.DateOfBirth.Year &gt; 1900
                           &amp;&amp; dr.DateOfBirth.Year &lt;= 2000
                           select new { dr.LastName, dr.FirstName };

foreach (var item in bornInThe20thCentury)
{
    Console.WriteLine(&quot;{0} {1}&quot;, item.FirstName, item.LastName);
}
</pre></p>
<p>Now that you understand the basic principles for creating custom dynamic objects, you can imagine many more useful applications <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><strong>Update :</strong> Just after posting this article, I stumbled upon the <a href="http://msdn.microsoft.com/en-us/library/system.dynamic.expandoobject%28VS.100%29.aspx"><code>ExpandoObject</code></a> class, which does exactly the same thing as the <code>MyDynamicObject</code> class above&#8230; It seems I reinvented the wheel again <img src='http://s1.wp.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> . Anyway, it&#8217;s interesting to see how dynamic objects work internally, if only for learning purposes&#8230; For more details about the <code>ExpandoObject</code> class, check out <a href="http://blogs.msdn.com/csharpfaq/archive/2009/10/01/dynamic-in-c-4-0-introducing-the-expandoobject.aspx">this post on the C# FAQ blog</a>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tomlev2.wordpress.com/237/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tomlev2.wordpress.com/237/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tomlev2.wordpress.com/237/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tomlev2.wordpress.com/237/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/tomlev2.wordpress.com/237/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/tomlev2.wordpress.com/237/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/tomlev2.wordpress.com/237/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/tomlev2.wordpress.com/237/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tomlev2.wordpress.com/237/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tomlev2.wordpress.com/237/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tomlev2.wordpress.com/237/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tomlev2.wordpress.com/237/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tomlev2.wordpress.com/237/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tomlev2.wordpress.com/237/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tomlev2.wordpress.com&amp;blog=7442815&amp;post=237&amp;subd=tomlev2&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://tomlev2.wordpress.com/2009/10/08/c-4-0-implementing-a-custom-dynamic-object/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f4acdb91aba11ddf8f03d4b12453f3d5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tomlev</media:title>
		</media:content>
	</item>
		<item>
		<title>[WPF] Markup extensions and templates</title>
		<link>http://tomlev2.wordpress.com/2009/08/23/wpf-markup-extensions-and-templates/</link>
		<comments>http://tomlev2.wordpress.com/2009/08/23/wpf-markup-extensions-and-templates/#comments</comments>
		<pubDate>Sun, 23 Aug 2009 01:51:10 +0000</pubDate>
		<dc:creator>Thomas Levesque</dc:creator>
				<category><![CDATA[Code sample]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[markup extension]]></category>
		<category><![CDATA[template]]></category>
		<category><![CDATA[XAML]]></category>

		<guid isPermaLink="false">http://tomlev2.wordpress.com/?p=228</guid>
		<description><![CDATA[Note&#160;: This post follows the one about a a markup extension that can update its target, and reuses the same code. You may have noticed that using a custom markup extension in a template sometimes lead to unexpected results&#8230; In this post I&#8217;ll explain what the problem is, and how to create a markup extensions [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tomlev2.wordpress.com&amp;blog=7442815&amp;post=228&amp;subd=tomlev2&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><em>Note&nbsp;: This post follows the one about a <a href="http://tomlev2.wordpress.com/2009/07/28/wpf-a-markup-extension-that-can-update-its-target/">a markup extension that can update its target</a>, and reuses the same code.</em></p>
<p>You may have noticed that using a custom markup extension in a template sometimes lead to unexpected results&#8230; In this post I&#8217;ll explain what the problem is, and how to create a markup extensions that behaves correctly in a template.</p>
<p><strong>The problem</strong></p>
<p>Let&#8217;s take the example from the previous post&nbsp;: a markup extension which gives the state of network connectivity, and updates its target when the network is connected or disconnected&nbsp;:</p>
<p><pre class="brush: xml;">
&lt;CheckBox IsChecked=&quot;{my:NetworkAvailable}&quot; Content=&quot;Network is available&quot; /&gt;
</pre></p>
<p>Now let&#8217;s put the same <code>CheckBox</code> in a <code>ControlTemplate</code>&nbsp;:</p>
<p><pre class="brush: xml;">
&lt;ControlTemplate x:Key=&quot;test&quot;&gt;
  &lt;CheckBox IsChecked=&quot;{my:NetworkAvailable}&quot; Content=&quot;Network is available&quot; /&gt;
&lt;/ControlTemplate&gt;
</pre></p>
<p>And let&#8217;s create a control which uses this template&nbsp;:</p>
<p><pre class="brush: xml;">
&lt;Control Template=&quot;{StaticResource test}&quot; /&gt;
</pre></p>
<p>If we disconnect from the network, we notice that the <code>CheckBox</code> is not automatically updated by the <code>NetworkAvailableExtension</code>, whereas it was working fine when we used it outside the template&#8230;</p>
<p><strong>Explanation and solution</strong></p>
<p>The markup expression is evaluated when it is encountered by the XAML parser&nbsp;: in that case, when the template is parsed. But at this time, the <code>CheckBox</code> control is not created yet, so the <code>ProvideValue</code> method can&#8217;t access it&#8230; When a markup extension is evaluated inside a template, the <code>TargetObject</code> is actually an instance of <code>System.Windows.SharedDp</code>, an internal WPF class.</p>
<p>For the markup extension to be able to access its target, it has to be evaluated when the template is applied&nbsp;: we need to defer its evaluation until this time. It&#8217;s actually pretty simple, we just need to return the markup extension itself from <code>ProvideValue</code>&nbsp;: this way, it will be evaluated again when the actual target control is created.</p>
<p>To check if the extension is evaluated for the template or for a &#8220;real&#8221; control, we just need to test whether the type of the <code>TargetObject</code> is <code>System.Windows.SharedDp</code>. So the code of the <code>ProvideValue</code> method becomes&nbsp;:</p>
<p><pre class="brush: csharp;">
        public sealed override object ProvideValue(IServiceProvider serviceProvider)
        {
            IProvideValueTarget target = serviceProvider.GetService(typeof(IProvideValueTarget)) as IProvideValueTarget;
            if (target != null)
            {
                if (target.TargetObject.GetType().FullName == &quot;System.Windows.SharedDp&quot;)
                    return this;
                _targetObject = target.TargetObject;
                _targetProperty = target.TargetProperty;
            }

            return ProvideValueInternal(serviceProvider);
        }
</pre></p>
<p>Cool, it&#8217;s now fixed, the <code>CheckBox</code> is updated when the network connectivity changes <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><strong>Last, but not least</strong></p>
<p>OK, we have a solution that apparently works fine, but let&#8217;s not count our chickens before they&#8217;re hatched&#8230; What if we now want to use our <code>ControlTemplate</code> on several controls ?</p>
<p><pre class="brush: xml;">
&lt;Control Template=&quot;{StaticResource test}&quot; /&gt;
&lt;Control Template=&quot;{StaticResource test}&quot; /&gt;
</pre></p>
<p>Now let&#8217;s run the application and unplug the network cable : the second <code>CheckBox</code> is updated, but the first one is not&#8230;</p>
<p>The reason for this is simple : there are two <code>CheckBox</code> controls, but only one instance of <code>NetworkAvailableExtension</code>, shared between all instances of the template. Now, <code>NetworkAvailableExtension</code> can only reference one target object, so only the last one for which <code>ProvideValue</code> has been called is kept&#8230;</p>
<p>So we need to keep track of not one target object, but a collection of target objects, which will all be update by the <code>UpdateValue</code> method. Here&#8217;s the final code of the <code>UpdatableMarkupExtension</code> base class&nbsp;:</p>
<p><pre class="brush: csharp; collapse: true; light: false; toolbar: true;">
    public abstract class UpdatableMarkupExtension : MarkupExtension
    {
        private List&lt;object&gt; _targetObjects = new List&lt;object&gt;();
        private object _targetProperty;

        protected IEnumerable&lt;object&gt; TargetObjects
        {
            get { return _targetObjects; }
        }

        protected object TargetProperty
        {
            get { return _targetProperty; }
        }

        public sealed override object ProvideValue(IServiceProvider serviceProvider)
        {
            // Retrieve target information
            IProvideValueTarget target = serviceProvider.GetService(typeof(IProvideValueTarget)) as IProvideValueTarget;

            if (target != null &amp;&amp; target.TargetObject != null)
            {
                // In a template the TargetObject is a SharedDp (internal WPF class)
                // In that case, the markup extension itself is returned to be re-evaluated later
                if (target.TargetObject.GetType().FullName == &quot;System.Windows.SharedDp&quot;)
                    return this;

                // Save target information for later updates
                _targetObjects.Add(target.TargetObject);
                _targetProperty = target.TargetProperty;
            }

            // Delegate the work to the derived class
            return ProvideValueInternal(serviceProvider);
        }

        protected virtual void UpdateValue(object value)
        {
            if (_targetObjects.Count &gt; 0)
            {
                // Update the target property of each target object
                foreach (var target in _targetObjects)
                {
                    if (_targetProperty is DependencyProperty)
                    {
                        DependencyObject obj = target as DependencyObject;
                        DependencyProperty prop = _targetProperty as DependencyProperty;

                        Action updateAction = () =&gt; obj.SetValue(prop, value);

                        // Check whether the target object can be accessed from the
                        // current thread, and use Dispatcher.Invoke if it can't

                        if (obj.CheckAccess())
                            updateAction();
                        else
                            obj.Dispatcher.Invoke(updateAction);
                    }
                    else // _targetProperty is PropertyInfo
                    {
                        PropertyInfo prop = _targetProperty as PropertyInfo;
                        prop.SetValue(target, value, null);
                    }
                }
            }
        }

        protected abstract object ProvideValueInternal(IServiceProvider serviceProvider);
    }
</pre></p>
<p>The <code>UpdatableMarkupExtension</code> is now fully functional&#8230; until proved otherwise <img src='http://s1.wp.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> . This class makes a good starting point for any markup extension that needs to update its target, without having to worry about the low-level aspects of tracking and updating target objects.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tomlev2.wordpress.com/228/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tomlev2.wordpress.com/228/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tomlev2.wordpress.com/228/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tomlev2.wordpress.com/228/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/tomlev2.wordpress.com/228/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/tomlev2.wordpress.com/228/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/tomlev2.wordpress.com/228/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/tomlev2.wordpress.com/228/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tomlev2.wordpress.com/228/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tomlev2.wordpress.com/228/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tomlev2.wordpress.com/228/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tomlev2.wordpress.com/228/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tomlev2.wordpress.com/228/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tomlev2.wordpress.com/228/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tomlev2.wordpress.com&amp;blog=7442815&amp;post=228&amp;subd=tomlev2&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://tomlev2.wordpress.com/2009/08/23/wpf-markup-extensions-and-templates/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f4acdb91aba11ddf8f03d4b12453f3d5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tomlev</media:title>
		</media:content>
	</item>
		<item>
		<title>[WPF] Automatically sort a GridView (continued)</title>
		<link>http://tomlev2.wordpress.com/2009/08/04/wpf-automatically-sort-a-gridview-continued/</link>
		<comments>http://tomlev2.wordpress.com/2009/08/04/wpf-automatically-sort-a-gridview-continued/#comments</comments>
		<pubDate>Tue, 04 Aug 2009 14:41:01 +0000</pubDate>
		<dc:creator>Thomas Levesque</dc:creator>
				<category><![CDATA[Code sample]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[attached property]]></category>
		<category><![CDATA[GridView]]></category>
		<category><![CDATA[sort]]></category>
		<category><![CDATA[XAML]]></category>

		<guid isPermaLink="false">http://tomlev2.wordpress.com/?p=223</guid>
		<description><![CDATA[A few months ago, I wrote a post where I explained how to automatically sort a GridView when a column header is clicked. I had mentioned a possible improvement : add a sort glyph in the column header to show which column is sorted. In today&#8217;s post, I present a new version of the GridViewSort [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tomlev2.wordpress.com&amp;blog=7442815&amp;post=223&amp;subd=tomlev2&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>A few months ago, I wrote <a href="http://tomlev2.wordpress.com/2009/03/27/wpf-automatically-sort-a-gridview-when-a-column-header-is-clicked/"><strong>a post</strong></a> where I explained how to automatically sort a GridView when a column header is clicked. I had mentioned a possible improvement : add a sort glyph in the column header to show which column is sorted. In today&#8217;s post, I present a new version of the <code>GridViewSort</code> class, which displays the sort glyph.</p>
<div id="attachment_224" class="wp-caption alignnone" style="width: 424px"><img src="http://tomlev2.files.wordpress.com/2009/08/gridviewsort_en.png?w=780" alt="GridViewSort sample with sort glyph" title="GridViewSort sample with sort glyph"   class="size-full wp-image-224" /><p class="wp-caption-text">GridViewSort sample with sort glyph</p></div>
<p>To achieve this result, I used an <code>Adorner</code> : this is a component which allows to draw over existing UI elements, on an independant rendering layer.</p>
<p>The new version of the <code>GridViewSort</code> class can be used as before, in that case the grid displays default sort glyphs. These default glyphs are not particularly good-looking, so if you have some artistic skills you can provide you own images, as shown in the code below :</p>
<p><pre class="brush: xml;">
        &lt;ListView ItemsSource=&quot;{Binding Persons}&quot;
                  IsSynchronizedWithCurrentItem=&quot;True&quot;
                  util:GridViewSort.AutoSort=&quot;True&quot;
                  util:GridViewSort.SortGlyphAscending=&quot;/Images/up.png&quot;
                  util:GridViewSort.SortGlyphDescending=&quot;/Images/down.png&quot;&gt;</pre></p>
<p>It is also possible to disable the sort glyphs, by setting the <code>ShowSortGlyph</code> attached property to <code>false</code> :</p>
<p><pre class="brush: xml;">
        &lt;ListView ItemsSource=&quot;{Binding Persons}&quot;
                  IsSynchronizedWithCurrentItem=&quot;True&quot;
                  util:GridViewSort.AutoSort=&quot;True&quot;
                  util:GridViewSort.ShowSortGlyph=&quot;False&quot;&gt;
</pre></p>
<p>Note that in the current version, the sort glyph is only displayed when using the automatic sort mode (<code>AutoSort</code> = <code>true</code>). The case of a custom sort using the <code>Command</code> property is not handled yet.</p>
<p>Here is the complete code of the new version of the class :</p>
<p><pre class="brush: csharp; collapse: true; light: false; toolbar: true;">
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Documents;

namespace Wpf.Util
{
    public class GridViewSort
    {
        #region Public attached properties

        public static ICommand GetCommand(DependencyObject obj)
        {
            return (ICommand)obj.GetValue(CommandProperty);
        }

        public static void SetCommand(DependencyObject obj, ICommand value)
        {
            obj.SetValue(CommandProperty, value);
        }

        // Using a DependencyProperty as the backing store for Command.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty CommandProperty =
            DependencyProperty.RegisterAttached(
                &quot;Command&quot;,
                typeof(ICommand),
                typeof(GridViewSort),
                new UIPropertyMetadata(
                    null,
                    (o, e) =&gt;
                    {
                        ItemsControl listView = o as ItemsControl;
                        if (listView != null)
                        {
                            if (!GetAutoSort(listView)) // Don't change click handler if AutoSort enabled
                            {
                                if (e.OldValue != null &amp;&amp; e.NewValue == null)
                                {
                                    listView.RemoveHandler(GridViewColumnHeader.ClickEvent, new RoutedEventHandler(ColumnHeader_Click));
                                }
                                if (e.OldValue == null &amp;&amp; e.NewValue != null)
                                {
                                    listView.AddHandler(GridViewColumnHeader.ClickEvent, new RoutedEventHandler(ColumnHeader_Click));
                                }
                            }
                        }
                    }
                )
            );

        public static bool GetAutoSort(DependencyObject obj)
        {
            return (bool)obj.GetValue(AutoSortProperty);
        }

        public static void SetAutoSort(DependencyObject obj, bool value)
        {
            obj.SetValue(AutoSortProperty, value);
        }

        // Using a DependencyProperty as the backing store for AutoSort.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty AutoSortProperty =
            DependencyProperty.RegisterAttached(
                &quot;AutoSort&quot;,
                typeof(bool),
                typeof(GridViewSort),
                new UIPropertyMetadata(
                    false,
                    (o, e) =&gt;
                    {
                        ListView listView = o as ListView;
                        if (listView != null)
                        {
                            if (GetCommand(listView) == null) // Don't change click handler if a command is set
                            {
                                bool oldValue = (bool)e.OldValue;
                                bool newValue = (bool)e.NewValue;
                                if (oldValue &amp;&amp; !newValue)
                                {
                                    listView.RemoveHandler(GridViewColumnHeader.ClickEvent, new RoutedEventHandler(ColumnHeader_Click));
                                }
                                if (!oldValue &amp;&amp; newValue)
                                {
                                    listView.AddHandler(GridViewColumnHeader.ClickEvent, new RoutedEventHandler(ColumnHeader_Click));
                                }
                            }
                        }
                    }
                )
            );

        public static string GetPropertyName(DependencyObject obj)
        {
            return (string)obj.GetValue(PropertyNameProperty);
        }

        public static void SetPropertyName(DependencyObject obj, string value)
        {
            obj.SetValue(PropertyNameProperty, value);
        }

        // Using a DependencyProperty as the backing store for PropertyName.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty PropertyNameProperty =
            DependencyProperty.RegisterAttached(
                &quot;PropertyName&quot;,
                typeof(string),
                typeof(GridViewSort),
                new UIPropertyMetadata(null)
            );

        public static bool GetShowSortGlyph(DependencyObject obj)
        {
            return (bool)obj.GetValue(ShowSortGlyphProperty);
        }

        public static void SetShowSortGlyph(DependencyObject obj, bool value)
        {
            obj.SetValue(ShowSortGlyphProperty, value);
        }

        // Using a DependencyProperty as the backing store for ShowSortGlyph.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ShowSortGlyphProperty =
            DependencyProperty.RegisterAttached(&quot;ShowSortGlyph&quot;, typeof(bool), typeof(GridViewSort), new UIPropertyMetadata(true));

        public static ImageSource GetSortGlyphAscending(DependencyObject obj)
        {
            return (ImageSource)obj.GetValue(SortGlyphAscendingProperty);
        }

        public static void SetSortGlyphAscending(DependencyObject obj, ImageSource value)
        {
            obj.SetValue(SortGlyphAscendingProperty, value);
        }

        // Using a DependencyProperty as the backing store for SortGlyphAscending.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty SortGlyphAscendingProperty =
            DependencyProperty.RegisterAttached(&quot;SortGlyphAscending&quot;, typeof(ImageSource), typeof(GridViewSort), new UIPropertyMetadata(null));

        public static ImageSource GetSortGlyphDescending(DependencyObject obj)
        {
            return (ImageSource)obj.GetValue(SortGlyphDescendingProperty);
        }

        public static void SetSortGlyphDescending(DependencyObject obj, ImageSource value)
        {
            obj.SetValue(SortGlyphDescendingProperty, value);
        }

        // Using a DependencyProperty as the backing store for SortGlyphDescending.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty SortGlyphDescendingProperty =
            DependencyProperty.RegisterAttached(&quot;SortGlyphDescending&quot;, typeof(ImageSource), typeof(GridViewSort), new UIPropertyMetadata(null));

        #endregion

        #region Private attached properties

        private static GridViewColumnHeader GetSortedColumnHeader(DependencyObject obj)
        {
            return (GridViewColumnHeader)obj.GetValue(SortedColumnHeaderProperty);
        }

        private static void SetSortedColumnHeader(DependencyObject obj, GridViewColumnHeader value)
        {
            obj.SetValue(SortedColumnHeaderProperty, value);
        }

        // Using a DependencyProperty as the backing store for SortedColumn.  This enables animation, styling, binding, etc...
        private static readonly DependencyProperty SortedColumnHeaderProperty =
            DependencyProperty.RegisterAttached(&quot;SortedColumnHeader&quot;, typeof(GridViewColumnHeader), typeof(GridViewSort), new UIPropertyMetadata(null));

        #endregion

        #region Column header click event handler

        private static void ColumnHeader_Click(object sender, RoutedEventArgs e)
        {
            GridViewColumnHeader headerClicked = e.OriginalSource as GridViewColumnHeader;
            if (headerClicked != null &amp;&amp; headerClicked.Column != null)
            {
                string propertyName = GetPropertyName(headerClicked.Column);
                if (!string.IsNullOrEmpty(propertyName))
                {
                    ListView listView = GetAncestor&lt;ListView&gt;(headerClicked);
                    if (listView != null)
                    {
                        ICommand command = GetCommand(listView);
                        if (command != null)
                        {
                            if (command.CanExecute(propertyName))
                            {
                                command.Execute(propertyName);
                            }
                        }
                        else if (GetAutoSort(listView))
                        {
                            ApplySort(listView.Items, propertyName, listView, headerClicked);
                        }
                    }
                }
            }
        }

        #endregion

        #region Helper methods

        public static T GetAncestor&lt;T&gt;(DependencyObject reference) where T : DependencyObject
        {
            DependencyObject parent = VisualTreeHelper.GetParent(reference);
            while (!(parent is T))
            {
                parent = VisualTreeHelper.GetParent(parent);
            }
            if (parent != null)
                return (T)parent;
            else
                return null;
        }

        public static void ApplySort(ICollectionView view, string propertyName, ListView listView, GridViewColumnHeader sortedColumnHeader)
        {
            ListSortDirection direction = ListSortDirection.Ascending;
            if (view.SortDescriptions.Count &gt; 0)
            {
                SortDescription currentSort = view.SortDescriptions[0];
                if (currentSort.PropertyName == propertyName)
                {
                    if (currentSort.Direction == ListSortDirection.Ascending)
                        direction = ListSortDirection.Descending;
                    else
                        direction = ListSortDirection.Ascending;
                }
                view.SortDescriptions.Clear();

                GridViewColumnHeader currentSortedColumnHeader = GetSortedColumnHeader(listView);
                if (currentSortedColumnHeader != null)
                {
                    RemoveSortGlyph(currentSortedColumnHeader);
                }
            }
            if (!string.IsNullOrEmpty(propertyName))
            {
                view.SortDescriptions.Add(new SortDescription(propertyName, direction));
                if (GetShowSortGlyph(listView))
                    AddSortGlyph(
                        sortedColumnHeader,
                        direction,
                        direction == ListSortDirection.Ascending ? GetSortGlyphAscending(listView) : GetSortGlyphDescending(listView));
                SetSortedColumnHeader(listView, sortedColumnHeader);
            }
        }

        private static void AddSortGlyph(GridViewColumnHeader columnHeader, ListSortDirection direction, ImageSource sortGlyph)
        {
            AdornerLayer adornerLayer = AdornerLayer.GetAdornerLayer(columnHeader);
            adornerLayer.Add(
                new SortGlyphAdorner(
                    columnHeader,
                    direction,
                    sortGlyph
                    ));
        }

        private static void RemoveSortGlyph(GridViewColumnHeader columnHeader)
        {
            AdornerLayer adornerLayer = AdornerLayer.GetAdornerLayer(columnHeader);
            Adorner[] adorners = adornerLayer.GetAdorners(columnHeader);
            if (adorners != null)
            {
                foreach (Adorner adorner in adorners)
                {
                    if (adorner is SortGlyphAdorner)
                        adornerLayer.Remove(adorner);
                }
            }
        }

        #endregion

        #region SortGlyphAdorner nested class

        private class SortGlyphAdorner : Adorner
        {
            private GridViewColumnHeader _columnHeader;
            private ListSortDirection _direction;
            private ImageSource _sortGlyph;

            public SortGlyphAdorner(GridViewColumnHeader columnHeader, ListSortDirection direction, ImageSource sortGlyph)
                : base(columnHeader)
            {
                _columnHeader = columnHeader;
                _direction = direction;
                _sortGlyph = sortGlyph;
            }

            private Geometry GetDefaultGlyph()
            {
                double x1 = _columnHeader.ActualWidth - 13;
                double x2 = x1 + 10;
                double x3 = x1 + 5;
                double y1 = _columnHeader.ActualHeight / 2 - 3;
                double y2 = y1 + 5;

                if (_direction == ListSortDirection.Ascending)
                {
                    double tmp = y1;
                    y1 = y2;
                    y2 = tmp;
                }

                PathSegmentCollection pathSegmentCollection = new PathSegmentCollection();
                pathSegmentCollection.Add(new LineSegment(new Point(x2, y1), true));
                pathSegmentCollection.Add(new LineSegment(new Point(x3, y2), true));

                PathFigure pathFigure = new PathFigure(
                    new Point(x1, y1),
                    pathSegmentCollection,
                    true);

                PathFigureCollection pathFigureCollection = new PathFigureCollection();
                pathFigureCollection.Add(pathFigure);

                PathGeometry pathGeometry = new PathGeometry(pathFigureCollection);
                return pathGeometry;
            }

            protected override void OnRender(DrawingContext drawingContext)
            {
                base.OnRender(drawingContext);

                if (_sortGlyph != null)
                {
                    double x = _columnHeader.ActualWidth - 13;
                    double y = _columnHeader.ActualHeight / 2 - 5;
                    Rect rect = new Rect(x, y, 10, 10);
                    drawingContext.DrawImage(_sortGlyph, rect);
                }
                else
                {
                    drawingContext.DrawGeometry(Brushes.LightGray, new Pen(Brushes.Gray, 1.0), GetDefaultGlyph());
                }
            }
        }

        #endregion
    }
}
</pre></p>
<p>I hope you&#8217;ll find that useful <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><strong>Update</strong>: uploaded <a href="http://tlevesque.developpez.com/files/AutoSortGridView.zip">example project</a> to demonstrate how to use the code</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tomlev2.wordpress.com/223/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tomlev2.wordpress.com/223/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tomlev2.wordpress.com/223/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tomlev2.wordpress.com/223/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/tomlev2.wordpress.com/223/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/tomlev2.wordpress.com/223/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/tomlev2.wordpress.com/223/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/tomlev2.wordpress.com/223/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tomlev2.wordpress.com/223/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tomlev2.wordpress.com/223/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tomlev2.wordpress.com/223/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tomlev2.wordpress.com/223/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tomlev2.wordpress.com/223/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tomlev2.wordpress.com/223/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tomlev2.wordpress.com&amp;blog=7442815&amp;post=223&amp;subd=tomlev2&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://tomlev2.wordpress.com/2009/08/04/wpf-automatically-sort-a-gridview-continued/feed/</wfw:commentRss>
		<slash:comments>49</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f4acdb91aba11ddf8f03d4b12453f3d5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tomlev</media:title>
		</media:content>

		<media:content url="http://tomlev2.files.wordpress.com/2009/08/gridviewsort_en.png" medium="image">
			<media:title type="html">GridViewSort sample with sort glyph</media:title>
		</media:content>
	</item>
		<item>
		<title>[WPF] A markup extension that can update its target</title>
		<link>http://tomlev2.wordpress.com/2009/07/28/wpf-a-markup-extension-that-can-update-its-target/</link>
		<comments>http://tomlev2.wordpress.com/2009/07/28/wpf-a-markup-extension-that-can-update-its-target/#comments</comments>
		<pubDate>Tue, 28 Jul 2009 12:38:26 +0000</pubDate>
		<dc:creator>Thomas Levesque</dc:creator>
				<category><![CDATA[Code sample]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[markup extension]]></category>
		<category><![CDATA[XAML]]></category>

		<guid isPermaLink="false">http://tomlev2.wordpress.com/?p=219</guid>
		<description><![CDATA[If you have read my previous posts on the topic, you know I&#8217;m a big fan of custom markup extensions&#8230; However, they have a limitation that can be quite annoying&#160;: they are only evaluated once. Yet it would be useful to be able to evaluate them again to update the target property, like a binding&#8230; [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tomlev2.wordpress.com&amp;blog=7442815&amp;post=219&amp;subd=tomlev2&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>If you have read my previous posts on the topic, you know I&#8217;m a big fan of custom markup extensions&#8230; However, they have a limitation that can be quite annoying&nbsp;: they are only evaluated once. Yet it would be useful to be able to evaluate them again to update the target property, like a binding&#8230; It could be useful in various cases, for instance&nbsp;:</p>
<ul>
<li>if the value of the markup extension can change in response to an event</li>
<li>if the state of the target object when the markup extension is evaluated doesn&#8217;t allow to determine the value yet, and the evaluation needs to be deferred (for instance, if the DataContext of the target object is needed, but is not yet defined when the markup extension is evaluated)</li>
</ul>
<p>This post explains how to update the target of a markup extension after the initial evaluation.</p>
<p>The  <code>ProvideValue</code> method of a markup extension takes a parameter of type <code>IServiceProvider</code>, which provides, among others, a <code>IProvideValueTarget</code> service. This interface exposes two properties, <code>TargetObject</code> and <code>TargetProperty</code>, which allow to retrieve the target object and property of the markup extension. It is then possible, if you retain this information, to update the property after the markup extension has already been evaluated.</p>
<p>To carry out this task, we can create an abstract class <code>UpdatableMarkupExtension</code>, which saves the target object and property, and provides a method to update the value&nbsp;:</p>
<p><pre class="brush: csharp;">
    public abstract class UpdatableMarkupExtension : MarkupExtension
    {
        private object _targetObject;
        private object _targetProperty;

        protected object TargetObject
        {
            get { return _targetObject; }
        }

        protected object TargetProperty
        {
            get { return _targetProperty; }
        }

        public sealed override object ProvideValue(IServiceProvider serviceProvider)
        {
            IProvideValueTarget target = serviceProvider.GetService(typeof(IProvideValueTarget)) as IProvideValueTarget;
            if (target != null)
            {
                _targetObject = target.TargetObject;
                _targetProperty = target.TargetProperty;
            }

            return ProvideValueInternal(serviceProvider);
        }

        protected void UpdateValue(object value)
        {
            if (_targetObject != null)
            {
                if (_targetProperty is DependencyProperty)
                {
                    DependencyObject obj = _targetObject as DependencyObject;
                    DependencyProperty prop = _targetProperty as DependencyProperty;

                    Action updateAction = () =&gt;  obj.SetValue(prop, value);

                    // Check whether the target object can be accessed from the
                    // current thread, and use Dispatcher.Invoke if it can't

                    if (obj.CheckAccess())
                        updateAction();
                    else
                        obj.Dispatcher.Invoke(updateAction);
                }
                else // _targetProperty is PropertyInfo
                {
                    PropertyInfo prop = _targetProperty as PropertyInfo;
                    prop.SetValue(_targetObject, value, null);
                }
            }
        }

        protected abstract object ProvideValueInternal(IServiceProvider serviceProvider);
    }
</pre></p>
<p>Since it is essential that the target object and property are saved, we mark the <code>ProvideValue</code> method as <code>sealed</code> so that it cannot be overriden, and we add an abstract <code>ProvideValueInternal</code> method so that inheritors can provide their implementation.</p>
<p>The <code>UpdateValue</code> method handles the update of the target property, which can be either a dependency property (<code>DependencyProperty</code>), or a standard CLR property (<code>PropertyInfo</code>). In the case of a <code>DependencyProperty</code>, the target object inherits from <code>DependencyObject</code>, which itself inherits from <code>DispatcherObject</code>&nbsp;: it is therefore necessary to make sure that the object is only accessed from the thread that owns it, using the <code>CheckAccess</code> and <code>Invoke</code> methods.</p>
<p>Here&#8217;s a simple example to illustrate how to use this class. Let&#8217;s assume we want to create a custom markup extension which indicates whether the network is available. It would be used like that&nbsp;:</p>
<p><pre class="brush: xml;">
&lt;CheckBox IsChecked=&quot;{my:NetworkAvailable}&quot; Content=&quot;Network is available&quot; /&gt;
</pre></p>
<p>Obviously, we want the checkbox to be updated when the availability of the network changes (e.g. when the network cable is plugged or unplugged, or when the Wifi network is out of reach). So we need to handle the <code>NetworkChange.NetworkAvailabilityChanged</code> event, and update the <code>IsChecked</code> property accordingly. So the extension will inherit the <code>UpdatableMarkupExtension</code> class to take advantage of the <code>UpdateValue</code> method&nbsp;:</p>
<p><pre class="brush: csharp;">
    public class NetworkAvailableExtension : UpdatableMarkupExtension
    {
        public NetworkAvailableExtension()
        {
            NetworkChange.NetworkAvailabilityChanged += new NetworkAvailabilityChangedEventHandler(NetworkChange_NetworkAvailabilityChanged);
        }

        protected override object ProvideValueInternal(IServiceProvider serviceProvider)
        {
            return NetworkInterface.GetIsNetworkAvailable();
        }

        private void NetworkChange_NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
        {
            UpdateValue(e.IsAvailable);
        }
    }
</pre></p>
<p>Note that we subscribe to the <code>NetworkAvailabilityChanged</code> event in the class constructor. If we wanted to subscribe to an event of the target object, we would have to do it in the <code>ProvideValueInternal</code> method, so that the target object can be accessed.</p>
<p>I hope this post let you see how simple it is to implement a markup extension that can update its target at a later time. This enables a behavior similar to a binding, but is not limited to dependency properties. An example of where I use this technique is to create a localization framework that allows to switch language &#8220;on the fly&#8221;, without restarting the application.</p>
<p><strong>Update&nbsp;:</strong><br />
In its current state, this markup extension can&#8217;t be used in a template. For an explanation and a solution to that issue, please read <a href="http://tomlev2.wordpress.com/2009/08/23/wpf-markup-extensions-and-templates/">this post</a>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tomlev2.wordpress.com/219/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tomlev2.wordpress.com/219/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tomlev2.wordpress.com/219/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tomlev2.wordpress.com/219/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/tomlev2.wordpress.com/219/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/tomlev2.wordpress.com/219/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/tomlev2.wordpress.com/219/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/tomlev2.wordpress.com/219/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tomlev2.wordpress.com/219/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tomlev2.wordpress.com/219/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tomlev2.wordpress.com/219/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tomlev2.wordpress.com/219/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tomlev2.wordpress.com/219/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tomlev2.wordpress.com/219/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tomlev2.wordpress.com&amp;blog=7442815&amp;post=219&amp;subd=tomlev2&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://tomlev2.wordpress.com/2009/07/28/wpf-a-markup-extension-that-can-update-its-target/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f4acdb91aba11ddf8f03d4b12453f3d5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tomlev</media:title>
		</media:content>
	</item>
		<item>
		<title>[C#] Parent/child relationship and XML serialization</title>
		<link>http://tomlev2.wordpress.com/2009/06/12/c-parentchild-relationship-and-xml-serialization/</link>
		<comments>http://tomlev2.wordpress.com/2009/06/12/c-parentchild-relationship-and-xml-serialization/#comments</comments>
		<pubDate>Fri, 12 Jun 2009 10:18:22 +0000</pubDate>
		<dc:creator>Thomas Levesque</dc:creator>
				<category><![CDATA[Code sample]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[collection]]></category>
		<category><![CDATA[parent/child]]></category>
		<category><![CDATA[XML serialization]]></category>

		<guid isPermaLink="false">http://tomlev2.wordpress.com/?p=212</guid>
		<description><![CDATA[Today I&#8217;d like to present an idea that occurred to me recently. Nothing about WPF this time, this is all about C# class design ! The problem It&#8217;s very common in C# programs to have an object that owns a collection of child items with a reference to their parent. For instance, this is the [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tomlev2.wordpress.com&amp;blog=7442815&amp;post=212&amp;subd=tomlev2&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Today I&#8217;d like to present an idea that occurred to me recently. Nothing about WPF this time, this is all about C# class design !</p>
<p><strong>The problem</strong></p>
<p>It&#8217;s very common in C# programs to have an object that owns a collection of child items with a reference to their parent. For instance, this is the case for Windows Forms controls, which have a collection of child controls (<code>Controls</code>), and a reference to their parent control (<code>Parent</code>).</p>
<p>This kind of structure is quite easy to implement, it just requires a bit of plumbing to maintain the consistency of the parent/child relationship. However, if you want to serialize the parent object to XML, it can get tricky&#8230; Let&#8217;s take a simple, purely theoretical example :</p>
<p><pre class="brush: csharp;">
    public class Parent
    {
        public Parent()
        {
            this.Children = new List&lt;Child&gt;();
        }

        public string Name { get; set; }

        public List&lt;Child&gt; Children { get; set; }

        public void AddChild(Child child)
        {
            child.ParentObject = this;
            this.Children.Add(child);
        }

        public void RemoveChild(Child child)
        {
            this.Children.Remove(child);
            child.ParentObject = null;
        }
    }
</pre></p>
<p><pre class="brush: csharp;">
    public class Child
    {
        public string Name { get; set; }

        public Parent ParentObject { get; set; }
    }
</pre></p>
<p>Let&#8217;s create an instance of <code>Parent</code> with a few children, and try to serialize it to XML :</p>
<p><pre class="brush: csharp;">
            Parent p = new Parent { Name = &quot;The parent&quot; };
            p.AddChild(new Child { Name = &quot;First child&quot; });
            p.AddChild(new Child { Name = &quot;Second child&quot; });

            string xml;
            XmlSerializer xs = new XmlSerializer(typeof(Parent));
            using (StringWriter wr = new StringWriter())
            {
                xs.Serialize(wr, p);
                xml = wr.ToString();
            }

            Console.WriteLine(xml);
</pre></p>
<p>When we try to serialize the <code>Parent</code> object, an <code>InvalidOperationException</code> occurs, saying that a circular reference was detected : indeed, the parent references the children, which in turn reference the parent, which references the children&#8230; and so on. The obvious solution to that issue is to suppress the serialization of the <code>Child.ParentObject</code> property, which can be done easily by using the <code>XmlIgnore</code> attribute. With that change the serialization works fine, but the problem is not solved yet : when we deserialize the object, the <code>ParentObject</code> property of the children is not set, since it wasn&#8217;t serialized&#8230; the consistency of the parent/child relationship is broken !</p>
<p>A simple and naive solution would be to loop through the <code>Children</code> collection after the deserialization, in order to set the <code>ParentObject</code> manually. But it&#8217;s definitely not an elegant approach&#8230; and since I really like elegant code, I thought of something else <img src='http://s1.wp.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p><strong>The solution</strong></p>
<p>The idea I had to solve this problem consists of a specialized generic collection <code>ChildItemCollection&lt;P,T&gt;</code>, and a <code>IChildItem&lt;P&gt;</code> interface that must be implemented by children.</p>
<p>The <code>IChildItem&lt;P&gt;</code> interface just defines a <code>Parent</code> property of type P :</p>
<p><pre class="brush: csharp;">
    /// &lt;summary&gt;
    /// Defines the contract for an object that has a parent object
    /// &lt;/summary&gt;
    /// &lt;typeparam name=&quot;P&quot;&gt;Type of the parent object&lt;/typeparam&gt;
    public interface IChildItem&lt;P&gt; where P : class
    {
        P Parent { get; set; }
    }
</pre></p>
<p>The <code>ChildItemCollection&lt;P,T&gt;</code> class implements <code>IList&lt;T&gt;</code> by delegating the implementation to a <code>List&lt;T&gt;</code> (or to a collection passed to the constructor), and maintains the parent/child relationship :</p>
<p><pre class="brush: csharp; collapse: true; light: false; toolbar: true;">
    /// &lt;summary&gt;
    /// Collection of child items. This collection automatically set the
    /// Parent property of the child items when they are added or removed
    /// &lt;/summary&gt;
    /// &lt;typeparam name=&quot;P&quot;&gt;Type of the parent object&lt;/typeparam&gt;
    /// &lt;typeparam name=&quot;T&quot;&gt;Type of the child items&lt;/typeparam&gt;
    public class ChildItemCollection&lt;P, T&gt; : IList&lt;T&gt;
        where P : class
        where T : IChildItem&lt;P&gt;
    {
        private P _parent;
        private IList&lt;T&gt; _collection;

        public ChildItemCollection(P parent)
        {
            this._parent = parent;
            this._collection = new List&lt;T&gt;();
        }

        public ChildItemCollection(P parent, IList&lt;T&gt; collection)
        {
            this._parent = parent;
            this._collection = collection;
        }

        #region IList&lt;T&gt; Members

        public int IndexOf(T item)
        {
            return _collection.IndexOf(item);
        }

        public void Insert(int index, T item)
        {
            if (item != null)
                item.Parent = _parent;
            _collection.Insert(index, item);
        }

        public void RemoveAt(int index)
        {
            T oldItem = _collection[index];
            _collection.RemoveAt(index);
            if (oldItem != null)
                oldItem.Parent = null;
        }

        public T this[int index]
        {
            get
            {
                return _collection[index];
            }
            set
            {
                T oldItem = _collection[index];
                if (value != null)
                    value.Parent = _parent;
                _collection[index] = value;
                if (oldItem != null)
                    oldItem.Parent = null;
            }
        }

        #endregion

        #region ICollection&lt;T&gt; Members

        public void Add(T item)
        {
            if (item != null)
                item.Parent = _parent;
            _collection.Add(item);
        }

        public void Clear()
        {
            foreach (T item in _collection)
            {
                if (item != null)
                    item.Parent = null;
            }
            _collection.Clear();
        }

        public bool Contains(T item)
        {
            return _collection.Contains(item);
        }

        public void CopyTo(T[] array, int arrayIndex)
        {
            _collection.CopyTo(array, arrayIndex);
        }

        public int Count
        {
            get { return _collection.Count; }
        }

        public bool IsReadOnly
        {
            get { return _collection.IsReadOnly; }
        }

        public bool Remove(T item)
        {
            bool b = _collection.Remove(item);
            if (item != null)
                item.Parent = null;
            return b;
        }

        #endregion

        #region IEnumerable&lt;T&gt; Members

        public IEnumerator&lt;T&gt; GetEnumerator()
        {
            return _collection.GetEnumerator();
        }

        #endregion

        #region IEnumerable Members

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return (_collection as System.Collections.IEnumerable).GetEnumerator();
        }

        #endregion
    }
</pre></p>
<p>Now let&#8217;s see how this class can be used in the case of the above example&#8230; First let&#8217;s change the <code>Child</code> class so that it implements the <code>IChildItem&lt;Parent&gt;</code> interface :</p>
<p><pre class="brush: csharp;">
    public class Child : IChildItem&lt;Parent&gt;
    {
        public string Name { get; set; }

        [XmlIgnore]
        public Parent ParentObject { get; internal set; }

        #region IChildItem&lt;Parent&gt; Members

        Parent IChildItem&lt;Parent&gt;.Parent
        {
            get
            {
                return this.ParentObject;
            }
            set
            {
                this.ParentObject = value;
            }
        }

        #endregion
    }
</pre></p>
<p>Note that here the <code>IChildItem&lt;Parent&gt;</code> interface is implemented <em>explicitly</em> : this is a way to &#8220;hide&#8221; the <code>Parent</code> property, that will only be accessible when manipulating the <code>Child</code> object through a variable of type <code>IChildItem&lt;Parent&gt;</code>. We also define the <code>set</code> accessor of the <code>ParentObject</code> property as <code>internal</code>, so that it can&#8217;t be modified from another assembly.</p>
<p>In the <code>Parent</code> class, the <code>List&lt;Child&gt;</code> just has to be replaced by a <code>ChildItemCollection&lt;Parent, Child&gt;</code>. We also remove the <code>AddChild</code> and <code>RemoveChild</code> methods, which are no more necessary since the <code>ChildItemCollection&lt;P,T&gt;</code> takes care of setting the <code>Parent</code> property.</p>
<p><pre class="brush: csharp;">
    public class Parent
    {
        public Parent()
        {
            this.Children = new ChildItemCollection&lt;Parent, Child&gt;(this);
        }

        public string Name { get; set; }

        public ChildItemCollection&lt;Parent, Child&gt; Children { get; private set; }
    }
</pre></p>
<p>Note that we give the <code>ChildItemCollection&lt;Parent, Child&gt;</code> constructor a reference to the current object : this is how the collection will know what is the parent of its elements.</p>
<p>The code previously used to serialize a <code>Parent</code> now works fine. During the deserialization, the <code>Child.ParentObject</code> property is not assigned when the <code>Child</code> itself is deserialized (since it has the <code>XmlIgnore</code> attribute), but when the <code>Child</code> is added to the <code>Parent.Children</code> collection.</p>
<p>Eventually, we can see that this solution enables us to keep the parent/child relationship when the object graph is serialized to XML, without resorting to unelegant tricks&#8230; However, note that the consistency of the relation can still be broken, if the <code>ParentObject</code> is changed by code outside the <code>ChildItemCollection&lt;P,T&gt;</code> class. To prevent that, some logic must be added to the <code>set</code> accessor to maintain the consistency ; I only omitted that part for the sake of clarity and simplicity.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tomlev2.wordpress.com/212/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tomlev2.wordpress.com/212/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tomlev2.wordpress.com/212/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tomlev2.wordpress.com/212/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/tomlev2.wordpress.com/212/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/tomlev2.wordpress.com/212/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/tomlev2.wordpress.com/212/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/tomlev2.wordpress.com/212/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tomlev2.wordpress.com/212/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tomlev2.wordpress.com/212/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tomlev2.wordpress.com/212/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tomlev2.wordpress.com/212/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tomlev2.wordpress.com/212/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tomlev2.wordpress.com/212/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tomlev2.wordpress.com&amp;blog=7442815&amp;post=212&amp;subd=tomlev2&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://tomlev2.wordpress.com/2009/06/12/c-parentchild-relationship-and-xml-serialization/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f4acdb91aba11ddf8f03d4b12453f3d5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tomlev</media:title>
		</media:content>
	</item>
		<item>
		<title>[Windows Forms] Automatically drag and drop controls (DragMove)</title>
		<link>http://tomlev2.wordpress.com/2009/05/06/windows-forms-automatically-drag-and-drop-controls-dragmove/</link>
		<comments>http://tomlev2.wordpress.com/2009/05/06/windows-forms-automatically-drag-and-drop-controls-dragmove/#comments</comments>
		<pubDate>Wed, 06 May 2009 00:17:21 +0000</pubDate>
		<dc:creator>Thomas Levesque</dc:creator>
				<category><![CDATA[Windows Forms]]></category>
		<category><![CDATA[dragmove]]></category>
		<category><![CDATA[windows forms]]></category>

		<guid isPermaLink="false">http://tomlev2.wordpress.com/?p=204</guid>
		<description><![CDATA[Here&#8217;s a piece of code I wrote a while ago, I just thought it could be useful for WinForms developers&#8230; In WPF, there is a very handy method to move a window with no borders : Window.DragMove. It can be used like that : When you call this method, the window is moved with the [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tomlev2.wordpress.com&amp;blog=7442815&amp;post=204&amp;subd=tomlev2&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s a piece of code I wrote a while ago, I just thought it could be useful for WinForms developers&#8230;</p>
<p>In WPF, there is a very handy method to move a window with no borders : <code>Window.DragMove</code>. It can be used like that :</p>
<p><pre class="brush: csharp;">
        private void Window_MouseDown(object sender, MouseButtonEventArgs e)
        {
            this.DragMove();
        }
</pre></p>
<p>When you call this method, the window is moved with the mouse until the button is released. It could hardly be simpler <img src='http://s1.wp.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>Unfortunately, this method only exists in WPF, and a majority of developers are still working with Windows Forms. So I came up with a solution to use a similar technique in Windows Forms, with a few improvements :</p>
<ul>
<li>Usable on any control, not only a window</li>
<li>No need to explicitly handle the <code>MouseDown</code> event</li>
<li>Form designer integration, using a <code>IExtenderProvider</code></li>
</ul>
<p>My solution consists of the following items :</p>
<ul>
<li>a static <code>DragMoveExtensions</code> class which provides extension methods for the <code>Control</code> class (easily convertible to regular static methods for use with C# 2)</li>
<li>a <code>DragMoveProvider</code> component, which implements <code>IExtenderProvider</code> to add a new <code>EnableDragMove</code> property to controls</li>
</ul>
<p>There are several ways to use this solution, pick the one that best suits your needs :</p>
<ul>
<li>The simplest, which requires no coding at all : in design mode, drop a <code>DragMoveProvider</code> on the Form, and set the <code>EnableDragMove</code> property to <code>true</code> on the Form or control</li>
<div id="attachment_166" class="wp-caption aligncenter" style="width: 460px"><a href="http://tomlev.files.wordpress.com/2009/04/dragmoveprovider1.png"><img src="http://tomlev.files.wordpress.com/2009/04/dragmoveprovider1.png?w=780" alt="DragMoveProvider" title="DragMoveProvider"   class="size-full wp-image-166" /></a><p class="wp-caption-text">DragMoveProvider</p></div>
<li>The closest to WPF&#8217;s DragMove : in the handler of the <code>MouseDown</code> event, call the <code>DragMove</code> extension method on the Form or control to move</li>
<p><pre class="brush: csharp;">
        private void label2_MouseDown(object sender, MouseEventArgs e)
        {
            label2.DragMove();
        }
</pre></p>
<li>The most flexible : call the <code>EnableDragMove</code> extension method on the Form or control to move (no event handling needed).</li>
<p><pre class="brush: csharp;">
        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            this.EnableDragMove(checkBox1.Checked);
        }
</pre></p>
</ul>
<p>The attached Visual Studio solution contains the WinFormsDragMove library, and a test project to demonstrate the various ways to use this library. A C#2-compatible version of these projects is also included.</p>
<p><a href="http://tlevesque.developpez.com/files/DragMove.zip">Download source</a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tomlev2.wordpress.com/204/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tomlev2.wordpress.com/204/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tomlev2.wordpress.com/204/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tomlev2.wordpress.com/204/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/tomlev2.wordpress.com/204/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/tomlev2.wordpress.com/204/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/tomlev2.wordpress.com/204/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/tomlev2.wordpress.com/204/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tomlev2.wordpress.com/204/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tomlev2.wordpress.com/204/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tomlev2.wordpress.com/204/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tomlev2.wordpress.com/204/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tomlev2.wordpress.com/204/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tomlev2.wordpress.com/204/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tomlev2.wordpress.com&amp;blog=7442815&amp;post=204&amp;subd=tomlev2&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://tomlev2.wordpress.com/2009/05/06/windows-forms-automatically-drag-and-drop-controls-dragmove/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f4acdb91aba11ddf8f03d4b12453f3d5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tomlev</media:title>
		</media:content>

		<media:content url="http://tomlev.files.wordpress.com/2009/04/dragmoveprovider1.png" medium="image">
			<media:title type="html">DragMoveProvider</media:title>
		</media:content>
	</item>
		<item>
		<title>[WPF] Binding to an asynchronous collection</title>
		<link>http://tomlev2.wordpress.com/2009/04/17/wpf-binding-to-an-asynchronous-collection/</link>
		<comments>http://tomlev2.wordpress.com/2009/04/17/wpf-binding-to-an-asynchronous-collection/#comments</comments>
		<pubDate>Fri, 17 Apr 2009 01:00:19 +0000</pubDate>
		<dc:creator>Thomas Levesque</dc:creator>
				<category><![CDATA[Code sample]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[asynchronous]]></category>
		<category><![CDATA[binding]]></category>
		<category><![CDATA[collection]]></category>
		<category><![CDATA[MVVM]]></category>

		<guid isPermaLink="false">http://tomlev.wordpress.com/?p=143</guid>
		<description><![CDATA[As you may have noticed, it is not possible to modify the contents of an ObservableCollection on a separate thread if a view is bound to this collection : the CollectionView raises a NotSupportedException : This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread To [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tomlev2.wordpress.com&amp;blog=7442815&amp;post=143&amp;subd=tomlev2&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>As you may have noticed, it is not possible to modify the contents of an <code>ObservableCollection</code> on a separate thread if a view is bound to this collection : the <code>CollectionView</code> raises a <code>NotSupportedException</code> :</p>
<blockquote><p>This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread</p></blockquote>
<p>To illustrate this, let&#8217;s take a simple example : a <code>ListBox</code> bound to a collection of strings in the ViewModel :</p>
<p><pre class="brush: csharp;">
        private ObservableCollection&lt;string&gt; _strings = new ObservableCollection&lt;string&gt;();
        public ObservableCollection&lt;string&gt; Strings
        {
            get { return _strings; }
            set
            {
                _strings = value;
                OnPropertyChanged(&quot;Strings&quot;);
            }
        }
</pre></p>
<p><pre class="brush: xml;">
    &lt;ListBox ItemsSource=&quot;{Binding Strings}&quot;/&gt;
</pre></p>
<p>If we add items to this collection out of the main thread, we get the exception mentioned above. A possible solution would be to create a new collection, and assign it to the <code>Strings</code> property when it is filled, but in this case the UI won&#8217;t reflect progress : all items will appear in the <code>ListBox</code> at the same time after the collection is filled, instead of appearing as they are added to the collection. It can be annoying in some cases : for instance, if the <code>ListBox</code> is used to display search results, the user expects to see the results as they are found, like in Windows Search.</p>
<p>A simple way to achieve the desired behavior is to inherit <code>ObservableCollection</code> and override <code>OnCollectionChanged</code> and <code>OnPropertyChanged</code> so that the events are raised on the main thread (actually, the thread that created the collection). The <code>AsyncOperation</code> class is perfectly suited for this need : it allows to &#8220;post&#8221; a method call on the thread that created it. It is used, for instance, in the <code>BackgroundWorker</code> component, and in many asynchronous methods in the framework (<code>PictureBox.LoadAsync</code>, <code>WebClient.DownloadAsync</code>, etc&#8230;).</p>
<p>So, here&#8217;s the code of an <code>AsyncObservableCollection</code> class, that can be modified from any thread, and still notify the UI when it is modified :</p>
<p><pre class="brush: csharp;">
    public class AsyncObservableCollection&lt;T&gt; : ObservableCollection&lt;T&gt;
    {
        private AsyncOperation asyncOp = null;

        public AsyncObservableCollection()
        {
            CreateAsyncOp();
        }

        public AsyncObservableCollection(IEnumerable&lt;T&gt; list)
            : base(list)
        {
            CreateAsyncOp();
        }

        private void CreateAsyncOp()
        {
            // Create the AsyncOperation to post events on the creator thread
            asyncOp = AsyncOperationManager.CreateOperation(null);
        }

        protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
        {
            // Post the CollectionChanged event on the creator thread
            asyncOp.Post(RaiseCollectionChanged, e);
        }

        private void RaiseCollectionChanged(object param)
        {
            // We are in the creator thread, call the base implementation directly
           base.OnCollectionChanged((NotifyCollectionChangedEventArgs)param);
        }

        protected override void OnPropertyChanged(PropertyChangedEventArgs e)
        {
            // Post the PropertyChanged event on the creator thread
            asyncOp.Post(RaisePropertyChanged, e);
        }

        private void RaisePropertyChanged(object param)
        {
            // We are in the creator thread, call the base implementation directly
            base.OnPropertyChanged((PropertyChangedEventArgs)param);
        }
    }
</pre></p>
<p>The only constraint when using this class is that instances of the collection must be created on the UI thread, so that events are raised on that thread.</p>
<p>In the previous example, the only thing to change to make the collection modifiable across threads is the instantiation of the collection in the ViewModel :</p>
<p><pre class="brush: csharp;">
private ObservableCollection&lt;string&gt; _strings = new AsyncObservableCollection&lt;string&gt;();
</pre></p>
<p>The <code>ListBox</code> can now reflect in real-time the changes made on the collection.</p>
<p>Enjoy <img src='http://s1.wp.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p><strong>Update :</strong> I just found a bug in my implementation : in some cases, using <code>Post</code> to raise the event when the collection is modified from the main thread can cause unpredictable behavior. In that case, the event should of course be raised directly on the main thread, after checking that the current <code>SynchronizationContext</code> is the one in which the collection was created. This also made me realize that the <code>AsyncOperation</code> actually doesn&#8217;t bring any benefit : we can use the <code>SynchronizationContext</code> directly instead. So here&#8217;s the new implementation :</p>
<p><pre class="brush: csharp;">
    public class AsyncObservableCollection&lt;T&gt; : ObservableCollection&lt;T&gt;
    {
        private SynchronizationContext _synchronizationContext = SynchronizationContext.Current;

        public AsyncObservableCollection()
        {
        }

        public AsyncObservableCollection(IEnumerable&lt;T&gt; list)
            : base(list)
        {
        }

        protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
        {
            if (SynchronizationContext.Current == _synchronizationContext)
            {
                // Execute the CollectionChanged event on the current thread
                RaiseCollectionChanged(e);
            }
            else
            {
                // Post the CollectionChanged event on the creator thread
                _synchronizationContext.Post(RaiseCollectionChanged, e);
            }
        }

        private void RaiseCollectionChanged(object param)
        {
            // We are in the creator thread, call the base implementation directly
            base.OnCollectionChanged((NotifyCollectionChangedEventArgs)param);
        }

        protected override void OnPropertyChanged(PropertyChangedEventArgs e)
        {
            if (SynchronizationContext.Current == _synchronizationContext)
            {
                // Execute the PropertyChanged event on the current thread
                RaisePropertyChanged(e);
            }
            else
            {
                // Post the PropertyChanged event on the creator thread
                _synchronizationContext.Post(RaisePropertyChanged, e);
            }
        }

        private void RaisePropertyChanged(object param)
        {
            // We are in the creator thread, call the base implementation directly
            base.OnPropertyChanged((PropertyChangedEventArgs)param);
        }
    }
</pre></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tomlev2.wordpress.com/143/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tomlev2.wordpress.com/143/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tomlev2.wordpress.com/143/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tomlev2.wordpress.com/143/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/tomlev2.wordpress.com/143/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/tomlev2.wordpress.com/143/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/tomlev2.wordpress.com/143/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/tomlev2.wordpress.com/143/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tomlev2.wordpress.com/143/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tomlev2.wordpress.com/143/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tomlev2.wordpress.com/143/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tomlev2.wordpress.com/143/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tomlev2.wordpress.com/143/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tomlev2.wordpress.com/143/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tomlev2.wordpress.com&amp;blog=7442815&amp;post=143&amp;subd=tomlev2&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://tomlev2.wordpress.com/2009/04/17/wpf-binding-to-an-asynchronous-collection/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f4acdb91aba11ddf8f03d4b12453f3d5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tomlev</media:title>
		</media:content>
	</item>
		<item>
		<title>[WPF] Automatically sort a GridView when a column header is clicked</title>
		<link>http://tomlev2.wordpress.com/2009/03/27/wpf-automatically-sort-a-gridview-when-a-column-header-is-clicked/</link>
		<comments>http://tomlev2.wordpress.com/2009/03/27/wpf-automatically-sort-a-gridview-when-a-column-header-is-clicked/#comments</comments>
		<pubDate>Fri, 27 Mar 2009 01:00:31 +0000</pubDate>
		<dc:creator>Thomas Levesque</dc:creator>
				<category><![CDATA[Code sample]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[attached property]]></category>
		<category><![CDATA[GridView]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[sort]]></category>

		<guid isPermaLink="false">http://tomlev.wordpress.com/?p=121</guid>
		<description><![CDATA[It&#8217;s quite simple, in WPF, to present data in a grid, thanks to the GridView class. If you want to sort it, however, it gets a little harder&#8230; With the DataGridView in Windows Forms, it was &#8220;automagic&#8221; : when the user clicked a column header, the grid was automatically sorted. To achieve the same behavior [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tomlev2.wordpress.com&amp;blog=7442815&amp;post=121&amp;subd=tomlev2&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s quite simple, in WPF, to present data in a grid, thanks to the <code>GridView</code> class. If you want to sort it, however, it gets a little harder&#8230; With the <code>DataGridView</code> in Windows Forms, it was &#8220;automagic&#8221; : when the user clicked a column header, the grid was automatically sorted. To achieve the same behavior in WPF, you need to get your hands dirty&#8230; The method recommended by Microsoft is described in <a href="http://msdn.microsoft.com/en-us/library/ms745786.aspx">this article</a> ; it is based on the <code>Click</code> event of the <code>GridViewColumnHeader</code> class. In my view, this approach has two major drawbacks :</p>
<ul>
<li>The sorting must be done in code-behind, something we usually want to avoid if the application is designed according to the MVVM pattern. It also makes the code harder to reuse.</li>
<li>This method assumes that the text of the column header is also the name of the property to use as the sort criteria, which isn&#8217;t always true, far from it&#8230; We could use the <code>DisplayMemberBinding</code> of the column, but it&#8217;s not always set (for instance if a <code>CellTemplate</code> is defined instead).</li>
</ul>
<p>After spending a long time trying to find a flexible and elegant approach, I came up with an interesting solution. It consists of a class with a few attached properties that can be set in XAML.</p>
<p>This class can be used as follows :</p>
<p><pre class="brush: xml;">
    &lt;ListView ItemsSource=&quot;{Binding Persons}&quot;
          IsSynchronizedWithCurrentItem=&quot;True&quot;
          util:GridViewSort.AutoSort=&quot;True&quot;&gt;
        &lt;ListView.View&gt;
            &lt;GridView&gt;
                &lt;GridView.Columns&gt;
                    &lt;GridViewColumn Header=&quot;Name&quot;
                                    DisplayMemberBinding=&quot;{Binding Name}&quot;
                                    util:GridViewSort.PropertyName=&quot;Name&quot;/&gt;
                    &lt;GridViewColumn Header=&quot;First name&quot;
                                    DisplayMemberBinding=&quot;{Binding FirstName}&quot;
                                    util:GridViewSort.PropertyName=&quot;FirstName&quot;/&gt;
                    &lt;GridViewColumn Header=&quot;Date of birth&quot;
                                    DisplayMemberBinding=&quot;{Binding DateOfBirth}&quot;
                                    util:GridViewSort.PropertyName=&quot;DateOfBirth&quot;/&gt;
                &lt;/GridView.Columns&gt;
            &lt;/GridView&gt;
        &lt;/ListView.View&gt;
    &lt;/ListView&gt;
</pre></p>
<p>The <code>GridViewSort.AutoSort</code> property enables automatic sorting for the <code>ListView</code>. The <code>GridViewSort.PropertyName</code> property, defined for each column, indicates the property to use as the sort criteria. There is no extra code to write. A click on a column header triggers the sorting on this column ; if the ListView is already sorted on this column, the sort order is reversed.</p>
<p>In case you need to handle the sorting manually, I also added a <code>GridViewSort.Command</code> attached property. When used with the MVVM pattern, this property allows you to bind to a command declared in the ViewModel :</p>
<p><pre class="brush: xml;">
    &lt;ListView ItemsSource=&quot;{Binding Persons}&quot;
          IsSynchronizedWithCurrentItem=&quot;True&quot;
          util:GridViewSort.Command=&quot;{Binding SortCommand}&quot;&gt;
    ...
</pre></p>
<p>The sort command takes as parameter the name of the property to use as the sort criteria.</p>
<p>Note : if both the <code>Command</code> and <code>AutoSort</code> properties are set, <code>Command</code> has priority. <code>AutoSort</code> is ignored.</p>
<p>Here is the full code of the <code>GridViewSort</code> class :</p>
<p><pre class="brush: csharp; collapse: true; light: false; toolbar: true;">
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;

namespace Wpf.Util
{
    public class GridViewSort
    {
        #region Attached properties

        public static ICommand GetCommand(DependencyObject obj)
        {
            return (ICommand)obj.GetValue(CommandProperty);
        }

        public static void SetCommand(DependencyObject obj, ICommand value)
        {
            obj.SetValue(CommandProperty, value);
        }

        // Using a DependencyProperty as the backing store for Command.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty CommandProperty =
            DependencyProperty.RegisterAttached(
                &quot;Command&quot;,
                typeof(ICommand),
                typeof(GridViewSort),
                new UIPropertyMetadata(
                    null,
                    (o, e) =&gt;
                    {
                        ItemsControl listView = o as ItemsControl;
                        if (listView != null)
                        {
                            if (!GetAutoSort(listView)) // Don't change click handler if AutoSort enabled
                            {
                                if (e.OldValue != null &amp;&amp; e.NewValue == null)
                                {
                                    listView.RemoveHandler(GridViewColumnHeader.ClickEvent, new RoutedEventHandler(ColumnHeader_Click));
                                }
                                if (e.OldValue == null &amp;&amp; e.NewValue != null)
                                {
                                    listView.AddHandler(GridViewColumnHeader.ClickEvent, new RoutedEventHandler(ColumnHeader_Click));
                                }
                            }
                        }
                    }
                )
            );

        public static bool GetAutoSort(DependencyObject obj)
        {
            return (bool)obj.GetValue(AutoSortProperty);
        }

        public static void SetAutoSort(DependencyObject obj, bool value)
        {
            obj.SetValue(AutoSortProperty, value);
        }

        // Using a DependencyProperty as the backing store for AutoSort.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty AutoSortProperty =
            DependencyProperty.RegisterAttached(
                &quot;AutoSort&quot;,
                typeof(bool),
                typeof(GridViewSort),
                new UIPropertyMetadata(
                    false,
                    (o, e) =&gt;
                    {
                        ListView listView = o as ListView;
                        if (listView != null)
                        {
                            if (GetCommand(listView) == null) // Don't change click handler if a command is set
                            {
                                bool oldValue = (bool)e.OldValue;
                                bool newValue = (bool)e.NewValue;
                                if (oldValue &amp;&amp; !newValue)
                                {
                                    listView.RemoveHandler(GridViewColumnHeader.ClickEvent, new RoutedEventHandler(ColumnHeader_Click));
                                }
                                if (!oldValue &amp;&amp; newValue)
                                {
                                    listView.AddHandler(GridViewColumnHeader.ClickEvent, new RoutedEventHandler(ColumnHeader_Click));
                                }
                            }
                        }
                    }
                )
            );

        public static string GetPropertyName(DependencyObject obj)
        {
            return (string)obj.GetValue(PropertyNameProperty);
        }

        public static void SetPropertyName(DependencyObject obj, string value)
        {
            obj.SetValue(PropertyNameProperty, value);
        }

        // Using a DependencyProperty as the backing store for PropertyName.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty PropertyNameProperty =
            DependencyProperty.RegisterAttached(
                &quot;PropertyName&quot;,
                typeof(string),
                typeof(GridViewSort),
                new UIPropertyMetadata(null)
            );

        #endregion

        #region Column header click event handler

        private static void ColumnHeader_Click(object sender, RoutedEventArgs e)
        {
            GridViewColumnHeader headerClicked = e.OriginalSource as GridViewColumnHeader;
            if (headerClicked != null)
            {
                string propertyName = GetPropertyName(headerClicked.Column);
                if (!string.IsNullOrEmpty(propertyName))
                {
                    ListView listView = GetAncestor&lt;ListView&gt;(headerClicked);
                    if (listView != null)
                    {
                        ICommand command = GetCommand(listView);
                        if (command != null)
                        {
                            if (command.CanExecute(propertyName))
                            {
                                command.Execute(propertyName);
                            }
                        }
                        else if (GetAutoSort(listView))
                        {
                            ApplySort(listView.Items, propertyName);
                        }
                    }
                }
            }
        }

        #endregion

        #region Helper methods

        public static T GetAncestor&lt;T&gt;(DependencyObject reference) where T : DependencyObject
        {
            DependencyObject parent = VisualTreeHelper.GetParent(reference);
            while (!(parent is T))
            {
                parent = VisualTreeHelper.GetParent(parent);
            }
            if (parent != null)
                return (T)parent;
            else
                return null;
        }

        public static void ApplySort(ICollectionView view, string propertyName)
        {
            ListSortDirection direction = ListSortDirection.Ascending;
            if (view.SortDescriptions.Count &gt; 0)
            {
                SortDescription currentSort = view.SortDescriptions[0];
                if (currentSort.PropertyName == propertyName)
                {
                    if (currentSort.Direction == ListSortDirection.Ascending)
                        direction = ListSortDirection.Descending;
                    else
                        direction = ListSortDirection.Ascending;
                }
                view.SortDescriptions.Clear();
            }
            if (!string.IsNullOrEmpty(propertyName))
            {
                view.SortDescriptions.Add(new SortDescription(propertyName, direction));
            }
        }

        #endregion
    }
}
</pre></p>
<p>Of course, this class could probably be improved&#8230; for instance, we could add an arrow glyph on the sorted column (maybe by using an <code>Adorner</code>). Maybe I&#8217;ll do that someday&#8230; meanwhile, please feel free to use it <img src='http://s1.wp.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p><strong>Update :</strong> A new version that displays the sort glyph in the sorted column is now available in <a href="http://tomlev2.wordpress.com/2009/08/04/wpf-automatically-sort-a-gridview-continued/">this blog post</a>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tomlev2.wordpress.com/121/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tomlev2.wordpress.com/121/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tomlev2.wordpress.com/121/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tomlev2.wordpress.com/121/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/tomlev2.wordpress.com/121/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/tomlev2.wordpress.com/121/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/tomlev2.wordpress.com/121/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/tomlev2.wordpress.com/121/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tomlev2.wordpress.com/121/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tomlev2.wordpress.com/121/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tomlev2.wordpress.com/121/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tomlev2.wordpress.com/121/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tomlev2.wordpress.com/121/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tomlev2.wordpress.com/121/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tomlev2.wordpress.com&amp;blog=7442815&amp;post=121&amp;subd=tomlev2&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://tomlev2.wordpress.com/2009/03/27/wpf-automatically-sort-a-gridview-when-a-column-header-is-clicked/feed/</wfw:commentRss>
		<slash:comments>29</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f4acdb91aba11ddf8f03d4b12453f3d5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tomlev</media:title>
		</media:content>
	</item>
		<item>
		<title>[WPF] Using InputBindings with the MVVM pattern</title>
		<link>http://tomlev2.wordpress.com/2009/03/17/wpf-using-inputbindings-with-the-mvvm-pattern/</link>
		<comments>http://tomlev2.wordpress.com/2009/03/17/wpf-using-inputbindings-with-the-mvvm-pattern/#comments</comments>
		<pubDate>Tue, 17 Mar 2009 10:27:58 +0000</pubDate>
		<dc:creator>Thomas Levesque</dc:creator>
				<category><![CDATA[Code sample]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[InputBinding]]></category>
		<category><![CDATA[KeyBinding]]></category>
		<category><![CDATA[markup extension]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[XAML]]></category>

		<guid isPermaLink="false">http://tomlev.wordpress.com/?p=107</guid>
		<description><![CDATA[If you develop WPF applications according to the Model-View-ViewModel pattern, you may have faced this issue : in XAML, how to bind a key or mouse gesture to a ViewModel command ? The obvious and intuitive approach would be this one : Unfortunately, this code doesn&#8217;t work, for two reasons : The Command property is [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tomlev2.wordpress.com&amp;blog=7442815&amp;post=107&amp;subd=tomlev2&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>If you develop WPF applications according to the Model-View-ViewModel pattern, you may have faced this issue : in XAML, how to bind a key or mouse gesture to a ViewModel command ? The obvious and intuitive approach would be this one :</p>
<p><pre class="brush: xml;">
    &lt;UserControl.InputBindings&gt;
        &lt;KeyBinding Modifiers=&quot;Control&quot; Key=&quot;E&quot; Command=&quot;{Binding EditCommand}&quot;/&gt;
    &lt;/UserControl.InputBindings&gt;
</pre></p>
<p>Unfortunately, this code doesn&#8217;t work, for two reasons :</p>
<ol>
<li>The <code>Command</code> property is not a dependency property, so you cannot assign it through binding</li>
<li><code>InputBinding</code>s are not part of the logical or visual tree of the control, so they don&#8217;t inherit the <code>DataContext</code></li>
</ol>
<p>A solution would be to create the <code>InputBinding</code>s in the code-behind, but in the MVVM pattern we usually prefer to avoid this&#8230; I spent a long time looking for alternative solutions to do this in XAML, but most of them are quite complex and unintuitive. So I eventually came up with a markup extension that enables binding to ViewModel commands, anywhere in XAML, even for non-dependency properties or if the element doesn&#8217;t normally inherit the <code>DataContext</code></p>
<p>This extension is used like a regular binding :</p>
<p><pre class="brush: xml;">
    &lt;UserControl.InputBindings&gt;
        &lt;KeyBinding Modifiers=&quot;Control&quot; Key=&quot;E&quot; Command=&quot;{input:CommandBinding EditCommand}&quot;/&gt;
    &lt;/UserControl.InputBindings&gt;
</pre></p>
<p>(The <em>input</em> XML namespace is mapped to the CLR namespace where the markup extension is declared)</p>
<p>In order to write this extension, I had to cheat a little&#8230; I used Reflector to find some private fields that would allow to retrieve the <code>DataContext</code> of the root element. I then accessed those fields using reflection.</p>
<p>Here is the code of the markup extension :</p>
<p><pre class="brush: csharp; collapse: true; light: false; toolbar: true;">
using System;
using System.Reflection;
using System.Windows;
using System.Windows.Input;
using System.Windows.Markup;

namespace MVVMLib.Input
{
    [MarkupExtensionReturnType(typeof(ICommand))]
    public class CommandBindingExtension : MarkupExtension
    {
        public CommandBindingExtension()
        {
        }

        public CommandBindingExtension(string commandName)
        {
            this.CommandName = commandName;
        }

        [ConstructorArgument(&quot;commandName&quot;)]
        public string CommandName { get; set; }

        private object targetObject;
        private object targetProperty;

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            IProvideValueTarget provideValueTarget = serviceProvider.GetService(typeof(IProvideValueTarget)) as IProvideValueTarget;
            if (provideValueTarget != null)
            {
                targetObject = provideValueTarget.TargetObject;
                targetProperty = provideValueTarget.TargetProperty;
            }

            if (!string.IsNullOrEmpty(CommandName))
            {
                // The serviceProvider is actually a ProvideValueServiceProvider, which has a private field &quot;_context&quot; of type ParserContext
                ParserContext parserContext = GetPrivateFieldValue&lt;ParserContext&gt;(serviceProvider, &quot;_context&quot;);
                if (parserContext != null)
                {
                    // A ParserContext has a private field &quot;_rootElement&quot;, which returns the root element of the XAML file
                    FrameworkElement rootElement = GetPrivateFieldValue&lt;FrameworkElement&gt;(parserContext, &quot;_rootElement&quot;);
                    if (rootElement != null)
                    {
                        // Now we can retrieve the DataContext
                        object dataContext = rootElement.DataContext;

                        // The DataContext may not be set yet when the FrameworkElement is first created, and it may change afterwards,
                        // so we handle the DataContextChanged event to update the Command when needed
                        if (!dataContextChangeHandlerSet)
                        {
                            rootElement.DataContextChanged += new DependencyPropertyChangedEventHandler(rootElement_DataContextChanged);
                            dataContextChangeHandlerSet = true;
                        }

                        if (dataContext != null)
                        {
                            ICommand command = GetCommand(dataContext, CommandName);
                            if (command != null)
                                return command;
                        }
                    }
                }
            }

            // The Command property of an InputBinding cannot be null, so we return a dummy extension instead
            return DummyCommand.Instance;
        }

        private ICommand GetCommand(object dataContext, string commandName)
        {
            PropertyInfo prop = dataContext.GetType().GetProperty(commandName);
            if (prop != null)
            {
                ICommand command = prop.GetValue(dataContext, null) as ICommand;
                if (command != null)
                    return command;
            }
            return null;
        }

        private void AssignCommand(ICommand command)
        {
            if (targetObject != null &amp;&amp; targetProperty != null)
            {
                if (targetProperty is DependencyProperty)
                {
                    DependencyObject depObj = targetObject as DependencyObject;
                    DependencyProperty depProp = targetProperty as DependencyProperty;
                    depObj.SetValue(depProp, command);
                }
                else
                {
                    PropertyInfo prop = targetProperty as PropertyInfo;
                    prop.SetValue(targetObject, command, null);
                }
            }
        }

        private bool dataContextChangeHandlerSet = false;
        private void rootElement_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            FrameworkElement rootElement = sender as FrameworkElement;
            if (rootElement != null)
            {
                object dataContext = rootElement.DataContext;
                if (dataContext != null)
                {
                    ICommand command = GetCommand(dataContext, CommandName);
                    if (command != null)
                    {
                        AssignCommand(command);
                    }
                }
            }
        }

        private T GetPrivateFieldValue&lt;T&gt;(object target, string fieldName)
        {
            FieldInfo field = target.GetType().GetField(fieldName, BindingFlags.Instance | BindingFlags.NonPublic);
            if (field != null)
            {
                return (T)field.GetValue(target);
            }
            return default(T);
        }

        // A dummy command that does nothing...
        private class DummyCommand : ICommand
        {

            #region Singleton pattern

            private DummyCommand()
            {
            }

            private static DummyCommand _instance = null;
            public static DummyCommand Instance
            {
                get
                {
                    if (_instance == null)
                    {
                        _instance = new DummyCommand();
                    }
                    return _instance;
                }
            }

            #endregion

            #region ICommand Members

            public bool CanExecute(object parameter)
            {
                return false;
            }

            public event EventHandler CanExecuteChanged;

            public void Execute(object parameter)
            {
            }

            #endregion
        }
    }
}
</pre></p>
<p>However this solution has a limitation : it works only for the <code>DataContext</code> of the XAML root. So you can&#8217;t use it, for instance, to define an InputBinding on a control whose <code>DataContext</code> is also redefined, because the markup extension will access the root <code>DataContext</code>. It shouldn&#8217;t be a problem in most cases, but you need to be aware of that&#8230;</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tomlev2.wordpress.com/107/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tomlev2.wordpress.com/107/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tomlev2.wordpress.com/107/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tomlev2.wordpress.com/107/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/tomlev2.wordpress.com/107/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/tomlev2.wordpress.com/107/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/tomlev2.wordpress.com/107/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/tomlev2.wordpress.com/107/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tomlev2.wordpress.com/107/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tomlev2.wordpress.com/107/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tomlev2.wordpress.com/107/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tomlev2.wordpress.com/107/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tomlev2.wordpress.com/107/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tomlev2.wordpress.com/107/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tomlev2.wordpress.com&amp;blog=7442815&amp;post=107&amp;subd=tomlev2&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://tomlev2.wordpress.com/2009/03/17/wpf-using-inputbindings-with-the-mvvm-pattern/feed/</wfw:commentRss>
		<slash:comments>24</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f4acdb91aba11ddf8f03d4b12453f3d5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tomlev</media:title>
		</media:content>
	</item>
		<item>
		<title>[Visual Studio] Trick : make a project item a child item of another</title>
		<link>http://tomlev2.wordpress.com/2009/03/05/visual-studio-trick-make-a-project-item-a-child-item-of-another/</link>
		<comments>http://tomlev2.wordpress.com/2009/03/05/visual-studio-trick-make-a-project-item-a-child-item-of-another/#comments</comments>
		<pubDate>Thu, 05 Mar 2009 01:32:55 +0000</pubDate>
		<dc:creator>Thomas Levesque</dc:creator>
				<category><![CDATA[Tricks]]></category>
		<category><![CDATA[trick]]></category>
		<category><![CDATA[Visual Studio]]></category>

		<guid isPermaLink="false">http://tomlev.wordpress.com/?p=92</guid>
		<description><![CDATA[You probably noticed that, in a C# project tree, some items are placed &#8220;under&#8221; a parent item : it is the case, for instance, for files generated by a designer or wizard : The following trick shows how to apply the same behavior to your own files. Let&#8217;s assume that you want to customize the [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tomlev2.wordpress.com&amp;blog=7442815&amp;post=92&amp;subd=tomlev2&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>You probably noticed that, in a C# project tree, some items are placed &#8220;under&#8221; a parent item : it is the case, for instance, for files generated by a designer or wizard :</p>
<div id="attachment_94" class="wp-caption aligncenter" style="width: 273px"><img src="http://tomlev.files.wordpress.com/2009/03/project1.png?w=780" alt="Solution Explorer" title="Solution Explorer"   class="size-full wp-image-94" /><p class="wp-caption-text">Model1.Designer.cs is a child item of Model1.edmx</p></div>
<p>The following trick shows how to apply the same behavior to your own files.</p>
<p>Let&#8217;s assume that you want to customize the classes generated by the EDM designer. You can&#8217;t modify the <em>Model1.designer.cs</em> file, because you changes would be overwritten by the designer. So you create a new file, say <code>Model1.Custom.cs</code>, where you will write your custom code for the entity classes (using the <code>partial</code> keyword). By default, this file is placed at the root of the project :</p>
<div id="attachment_98" class="wp-caption aligncenter" style="width: 274px"><img src="http://tomlev.files.wordpress.com/2009/03/project23.png?w=780" alt="Solution Explorer" title="Solution Explorer"   class="size-full wp-image-98" /><p class="wp-caption-text">Model1.Custom.cs is at the root of the project</p></div>
<p>In order to show clearly the association with <em>Model1.edmx</em>, we would like to make <em>Model1.Custom.cs</em> a child item of <em>Model1.edmx</em>, at the same level as <em>Model1.designer.cs</em>&#8230; Even though the Visual Studio IDE doesn&#8217;t offer that option, it is possible : you just need to edit the <em>.csproj</em> file manually. The easiest way to do that is to unload the project (right click on the project, &#8220;<em>Unload project</em>&#8220;), and edit it directly in Visual Studio (right click, &#8220;<em>Edit FooBar.csproj</em>&#8220;). Find the <code>&lt;Compile&gt;</code> element corresponding to <em>Model1.Custom.cs</em>, and add a <code>&lt;DependentUpon&gt;</code> child element, as show below :</p>
<p><pre class="brush: xml;">
    &lt;Compile Include=&quot;Model1.Custom.cs&quot;&gt;
        &lt;DependentUpon&gt;Model1.edmx&lt;/DependentUpon&gt;
    &lt;/Compile&gt;
</pre></p>
<p>Reload the project : <em>Model1.Custom.cs</em> now appears as a child item of <em>Model1.edmx</em>.<br />
<div id="attachment_101" class="wp-caption aligncenter" style="width: 275px"><img src="http://tomlev.files.wordpress.com/2009/03/project3.png?w=780" alt="Solution Explorer" title="Solution Explorer"   class="size-full wp-image-101" /><p class="wp-caption-text">Model1.Custom.cs is now a child item of Model1.edmx</p></div></p>
<p>This trick enables you to organize your project better and make its structure clearer.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tomlev2.wordpress.com/92/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tomlev2.wordpress.com/92/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tomlev2.wordpress.com/92/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tomlev2.wordpress.com/92/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/tomlev2.wordpress.com/92/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/tomlev2.wordpress.com/92/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/tomlev2.wordpress.com/92/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/tomlev2.wordpress.com/92/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tomlev2.wordpress.com/92/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tomlev2.wordpress.com/92/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tomlev2.wordpress.com/92/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tomlev2.wordpress.com/92/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tomlev2.wordpress.com/92/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tomlev2.wordpress.com/92/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tomlev2.wordpress.com&amp;blog=7442815&amp;post=92&amp;subd=tomlev2&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://tomlev2.wordpress.com/2009/03/05/visual-studio-trick-make-a-project-item-a-child-item-of-another/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f4acdb91aba11ddf8f03d4b12453f3d5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tomlev</media:title>
		</media:content>

		<media:content url="http://tomlev.files.wordpress.com/2009/03/project1.png" medium="image">
			<media:title type="html">Solution Explorer</media:title>
		</media:content>

		<media:content url="http://tomlev.files.wordpress.com/2009/03/project23.png" medium="image">
			<media:title type="html">Solution Explorer</media:title>
		</media:content>

		<media:content url="http://tomlev.files.wordpress.com/2009/03/project3.png" medium="image">
			<media:title type="html">Solution Explorer</media:title>
		</media:content>
	</item>
		<item>
		<title>[WPF] Article about the Model-View-ViewModel design pattern, by Josh Smith</title>
		<link>http://tomlev2.wordpress.com/2009/02/25/wpf-article-about-model-view-viewmodel-design-pattern-by-josh-smith/</link>
		<comments>http://tomlev2.wordpress.com/2009/02/25/wpf-article-about-model-view-viewmodel-design-pattern-by-josh-smith/#comments</comments>
		<pubDate>Wed, 25 Feb 2009 01:30:56 +0000</pubDate>
		<dc:creator>Thomas Levesque</dc:creator>
				<category><![CDATA[WPF]]></category>
		<category><![CDATA[article]]></category>
		<category><![CDATA[design pattern]]></category>
		<category><![CDATA[Josh Smith]]></category>
		<category><![CDATA[MVVM]]></category>

		<guid isPermaLink="false">http://tomlev.wordpress.com/?p=79</guid>
		<description><![CDATA[Soon after the release of WPF, people have been talking more and more about &#8220;Model-View-ViewModel&#8221; (MVVM). This expression refers to a design pattern, drawing its inspiration from the Model-View-Controller (MVC) and Presentation Model (PM) patterns, and created specifically to take advantage of WPF features. This patterns enables an excellent decoupling between data, behavior and presentation, [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tomlev2.wordpress.com&amp;blog=7442815&amp;post=79&amp;subd=tomlev2&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Soon after the release of WPF, people have been talking more and more about &#8220;Model-View-ViewModel&#8221; (MVVM). This expression refers to a design pattern, drawing its inspiration from the Model-View-Controller (MVC) and Presentation Model (PM) patterns, and created specifically to take advantage of WPF features. This patterns enables an excellent decoupling between data, behavior and presentation, which makes the code easier to understand and maintain, and improves the collaboration between developers and designers. Another benefit of MVVM is the ability to write testable code much more easily.</p>
<p>If you want to know more about this pattern, I urge you to read the excellent article by Josh Smith on this topic, published in the February issue of the MSDN Magazine : <a href="http://msdn.microsoft.com/en-us/magazine/dd419663.aspx">WPF Apps With The Model-View-ViewModel Design Pattern</a>.</p>
<p>Walking through a simple but concrete example, Josh Smith addresses most aspects of the MVVM pattern :</p>
<ul>
<li>Data binding</li>
<li>Commands</li>
<li>Validation</li>
<li>Unit testing</li>
<li>&#8230;</li>
</ul>
<p>Further more, the provided source code makes a good starting point to build a WPF application conforming to the MVVM pattern, and is also a mine of practical examples.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tomlev2.wordpress.com/79/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tomlev2.wordpress.com/79/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tomlev2.wordpress.com/79/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tomlev2.wordpress.com/79/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/tomlev2.wordpress.com/79/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/tomlev2.wordpress.com/79/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/tomlev2.wordpress.com/79/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/tomlev2.wordpress.com/79/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tomlev2.wordpress.com/79/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tomlev2.wordpress.com/79/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tomlev2.wordpress.com/79/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tomlev2.wordpress.com/79/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tomlev2.wordpress.com/79/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tomlev2.wordpress.com/79/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tomlev2.wordpress.com&amp;blog=7442815&amp;post=79&amp;subd=tomlev2&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://tomlev2.wordpress.com/2009/02/25/wpf-article-about-model-view-viewmodel-design-pattern-by-josh-smith/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f4acdb91aba11ddf8f03d4b12453f3d5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tomlev</media:title>
		</media:content>
	</item>
		<item>
		<title>Build an RSS reader in 5 minutes</title>
		<link>http://tomlev2.wordpress.com/2009/02/13/build-an-rss-reader-in-5-minutes/</link>
		<comments>http://tomlev2.wordpress.com/2009/02/13/build-an-rss-reader-in-5-minutes/#comments</comments>
		<pubDate>Thu, 12 Feb 2009 23:05:13 +0000</pubDate>
		<dc:creator>Thomas Levesque</dc:creator>
				<category><![CDATA[Code sample]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[RSS]]></category>
		<category><![CDATA[syndication]]></category>

		<guid isPermaLink="false">http://tomlev.wordpress.com/?p=58</guid>
		<description><![CDATA[Today, I stumbled upon a very handy class : SyndicationFeed. This class, introduced in .NET 3.5, allows to manipulate syndication feeds (like RSS 2.0 or Atom 1.0) with very little code. It can be used to create and publish our own feeds, or to read existing ones. For instance, here&#8217;s how to retrieve the news [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tomlev2.wordpress.com&amp;blog=7442815&amp;post=58&amp;subd=tomlev2&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Today, I stumbled upon a very handy class : <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.syndication.syndicationfeed.aspx">SyndicationFeed</a>. This class, introduced in .NET 3.5, allows to manipulate syndication feeds (like RSS 2.0 or Atom 1.0) with very little code. It can be used to create and publish our own feeds, or to read existing ones.</p>
<p>For instance, here&#8217;s how to retrieve the news feed from Google News and display its title, its hyperlink, and the titles of it&#8217;s items :</p>
<p><pre class="brush: csharp;">
string url = &quot;http://news.google.fr/nwshp?hl=fr&amp;tab=wn&amp;output=rss&quot;;
using (XmlReader reader = XmlReader.Create(url))
{
    SyndicationFeed feed = SyndicationFeed.Load(reader);
    Console.WriteLine(feed.Title.Text);
    Console.WriteLine(feed.Links[0].Uri);
    foreach(SyndicationItem item in feed.Items)
    {
        Console.WriteLine(item.Title.Text);
    }
}</pre></p>
<p>Easy enough, don&#8217;t you think ? <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Let&#8217;s now take advantage of WPF binding capabilities to create a very simple graphical RSS reader :</p>
<p><pre class="brush: xml;">
&lt;Window x:Class=&quot;TestFeeds.Window1&quot;
        xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
        xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
        Title=&quot;Minimalist feed reader&quot; Height=&quot;286&quot; Width=&quot;531&quot;&gt;
    &lt;Grid&gt;
        &lt;Grid.RowDefinitions&gt;
            &lt;RowDefinition Height=&quot;Auto&quot;/&gt;
            &lt;RowDefinition Height=&quot;*&quot;/&gt;
        &lt;/Grid.RowDefinitions&gt;
        &lt;DockPanel Grid.Row=&quot;0&quot;&gt;
            &lt;Button Name=&quot;btnGo&quot;
                    DockPanel.Dock=&quot;Right&quot;
                    Width=&quot;50&quot;
                    Content=&quot;Go&quot;
                    Click=&quot;btnGo_Click&quot; /&gt;
            &lt;TextBox Name=&quot;txtUrl&quot; /&gt;
        &lt;/DockPanel&gt;
        &lt;Grid Grid.Row=&quot;1&quot;&gt;
            &lt;Grid.ColumnDefinitions&gt;
                &lt;ColumnDefinition Width=&quot;250&quot;/&gt;
                &lt;ColumnDefinition Width=&quot;Auto&quot;/&gt;
                &lt;ColumnDefinition Width=&quot;*&quot;/&gt;
            &lt;/Grid.ColumnDefinitions&gt;
            &lt;ListBox Name=&quot;lstFeedItems&quot;
                     Grid.Column=&quot;0&quot;
                     DisplayMemberPath=&quot;Title.Text&quot; /&gt;
            &lt;GridSplitter Grid.Column=&quot;1&quot;
                          VerticalAlignment=&quot;Stretch&quot;
                          Width=&quot;3&quot;
                          ResizeBehavior=&quot;PreviousAndNext&quot;
                          ResizeDirection=&quot;Columns&quot;/&gt;
            &lt;Frame Name=&quot;frmContents&quot;
                   Source=&quot;{Binding SelectedItem.Links[0].Uri, ElementName=lstFeedItems}&quot;
                   Grid.Column=&quot;2&quot;
                   NavigationUIVisibility=&quot;Visible&quot;&gt;
            &lt;/Frame&gt;
        &lt;/Grid&gt;
    &lt;/Grid&gt;
&lt;/Window&gt;
</pre></p>
<p>The code-behind :</p>
<p><pre class="brush: csharp;">
    private void btnGo_Click(object sender, RoutedEventArgs e)
    {
        using (XmlReader reader = XmlReader.Create(txtUrl.Text))
        {
            SyndicationFeed feed = SyndicationFeed.Load(reader);
            lstFeedItems.ItemsSource = feed.Items;
        }
    }
</pre></p>
<p>And here&#8217;s the result !</p>
<p><a href="http://tomlev.files.wordpress.com/2009/02/feed_reader.png"><img src="http://tomlev.files.wordpress.com/2009/02/feed_reader.png?w=780" border="0" alt="Screenshot" title="Screenshot"   class="aligncenter size-full wp-image-64" /></a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tomlev2.wordpress.com/58/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tomlev2.wordpress.com/58/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tomlev2.wordpress.com/58/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tomlev2.wordpress.com/58/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/tomlev2.wordpress.com/58/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/tomlev2.wordpress.com/58/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/tomlev2.wordpress.com/58/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/tomlev2.wordpress.com/58/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tomlev2.wordpress.com/58/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tomlev2.wordpress.com/58/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tomlev2.wordpress.com/58/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tomlev2.wordpress.com/58/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tomlev2.wordpress.com/58/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tomlev2.wordpress.com/58/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tomlev2.wordpress.com&amp;blog=7442815&amp;post=58&amp;subd=tomlev2&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://tomlev2.wordpress.com/2009/02/13/build-an-rss-reader-in-5-minutes/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f4acdb91aba11ddf8f03d4b12453f3d5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tomlev</media:title>
		</media:content>

		<media:content url="http://tomlev.files.wordpress.com/2009/02/feed_reader.png" medium="image">
			<media:title type="html">Screenshot</media:title>
		</media:content>
	</item>
		<item>
		<title>[WPF] Paste an image from the clipboard (bug in Clipboard.GetImage)</title>
		<link>http://tomlev2.wordpress.com/2009/02/05/wpf-paste-an-image-from-the-clipboard/</link>
		<comments>http://tomlev2.wordpress.com/2009/02/05/wpf-paste-an-image-from-the-clipboard/#comments</comments>
		<pubDate>Thu, 05 Feb 2009 00:26:28 +0000</pubDate>
		<dc:creator>Thomas Levesque</dc:creator>
				<category><![CDATA[Code sample]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[bug]]></category>
		<category><![CDATA[clipboard]]></category>
		<category><![CDATA[image]]></category>
		<category><![CDATA[workaround]]></category>

		<guid isPermaLink="false">http://tomlev.wordpress.com/?p=21</guid>
		<description><![CDATA[Oops&#8230; 2 months already since my previous (and first) post&#8230; I really have to get on a more regular schedule If you&#8217;ve ever tried to use the Clipboard.GetImage method in WPF, you probably had an unpleasant surprise&#8230; In fact, this method returns an InteropBitmap which, in some cases (most cases actually), can&#8217;t be displayed in [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tomlev2.wordpress.com&amp;blog=7442815&amp;post=21&amp;subd=tomlev2&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Oops&#8230; 2 months already since my previous (and first) post&#8230; I really have to get on a more regular schedule <img src='http://s1.wp.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>If you&#8217;ve ever tried to use the <code>Clipboard.GetImage</code> method in WPF, you probably had an unpleasant surprise&#8230; In fact, this method returns an <code>InteropBitmap</code> which, in some cases (most cases actually), can&#8217;t be displayed in an <code>Image</code> control : no exception is thrown, the image size is correct, but the image either appears empty or unrecognizable.</p>
<p>However, if we save that image to a stream and re-read it from the stream, we get a perfectly usable image&#8230; So this could be an acceptable workaround, but I think its pretty bad for performance, because the image gets decoded, re-encoded, and re-decoded. It is also possible to use the <code>Clipboard</code> class from Windows Forms, which works fine, and convert the <code>System.Drawing.Image</code> to a <code>System.Windows.Media.ImageSource</code>, but I don&#8217;t like the idea of referencing the Windows Forms assembly in a WPF app&#8230; So I decided to manually retrieve the image from the clipboard and handle the decoding myself.</p>
<p>If we look at the image formats available from the clipboard (<code>Clipboard.GetDataObject().GetFormats()</code>), we can see that they depend on the origin of the image (screenshot, copy from Paint&#8230;). The only format that is always available is <code>DeviceIndependentBitmap</code> (DIB). So I tried to retrieve the <code>MemoryStream</code> for this format and decode it into a <code>BitmapSource</code> :</p>
<p><pre class="brush: csharp;">
        private ImageSource ImageFromClipboardDib()
        {
            MemoryStream ms = Clipboard.GetData(&quot;DeviceIndependentBitmap&quot;) as MemoryStream;
            BitmapImage bmp = new BitmapImage();
            bmp.BeginInit();
            bmp.StreamSource = ms;
            bmp.EndInit();
            return bmp;
        }
</pre></p>
<p>Unfortunately, this code throws a nasty <code>NotSupportedException</code> : « No imaging component suitable to complete this operation was found ». In other words, it doesn&#8217;t know how to decode the contents of the stream&#8230; That&#8217;s quite surprising, because DIB is a very common format. So I had a look at the structure of a DIB in MSDN documentation. Basically, a « classical » bitmap file (.bmp) is made of the following sections :</p>
<ul>
<li>File header (<code>BITMAPFILEHEADER</code> structure)</li>
<li>Bitmap header (<code>BITMAPINFO</code> structure)</li>
<li>Palette (array of RGBQUAD)</li>
<li>Raw pixel data</li>
</ul>
<p>If we observe the content of the DIB from the clipboard, we can see that it has the same structure, without the <code>BITMAPFILEHEADER</code> part&#8230; so the trick is just to add that header at the beginning of the buffer, and use this complete buffer to decode the image. Doesn&#8217;t seem so hard, does it ? Well, the trouble is that we have to fill in some of the header fields&#8230; for instance, we must provide the location at which the actual image data begins, so we must know the total size of the headers and palette. These values can be read or calculated from the content of the image. The following code performs that task and returns an ImageSource from the clipboard :</p>
<p><pre class="brush: csharp;">
        private ImageSource ImageFromClipboardDib()
        {
            MemoryStream ms = Clipboard.GetData(&quot;DeviceIndependentBitmap&quot;) as MemoryStream;
            if (ms != null)
            {
                byte[] dibBuffer = new byte[ms.Length];
                ms.Read(dibBuffer, 0, dibBuffer.Length);

                BITMAPINFOHEADER infoHeader =
                    BinaryStructConverter.FromByteArray&lt;BITMAPINFOHEADER&gt;(dibBuffer);

                int fileHeaderSize = Marshal.SizeOf(typeof(BITMAPFILEHEADER));
                int infoHeaderSize = infoHeader.biSize;
                int fileSize = fileHeaderSize + infoHeader.biSize + infoHeader.biSizeImage;

                BITMAPFILEHEADER fileHeader = new BITMAPFILEHEADER();
                fileHeader.bfType = BITMAPFILEHEADER.BM;
                fileHeader.bfSize = fileSize;
                fileHeader.bfReserved1 = 0;
                fileHeader.bfReserved2 = 0;
                fileHeader.bfOffBits = fileHeaderSize + infoHeaderSize + infoHeader.biClrUsed * 4;

                byte[] fileHeaderBytes =
                    BinaryStructConverter.ToByteArray&lt;BITMAPFILEHEADER&gt;(fileHeader);

                MemoryStream msBitmap = new MemoryStream();
                msBitmap.Write(fileHeaderBytes, 0, fileHeaderSize);
                msBitmap.Write(dibBuffer, 0, dibBuffer.Length);
                msBitmap.Seek(0, SeekOrigin.Begin);

                return BitmapFrame.Create(msBitmap);
            }
            return null;
        }
</pre></p>
<p>Definition of the <code>BITMAPFILEHEADER</code> and <code>BITMAPINFOHEADER</code> structures :</p>
<p><pre class="brush: csharp;">
        [StructLayout(LayoutKind.Sequential, Pack = 2)]
        private struct BITMAPFILEHEADER
        {
            public static readonly short BM = 0x4d42; // BM

            public short bfType;
            public int bfSize;
            public short bfReserved1;
            public short bfReserved2;
            public int bfOffBits;
        }

        [StructLayout(LayoutKind.Sequential)]
        private struct BITMAPINFOHEADER
        {
            public int biSize;
            public int biWidth;
            public int biHeight;
            public short biPlanes;
            public short biBitCount;
            public int biCompression;
            public int biSizeImage;
            public int biXPelsPerMeter;
            public int biYPelsPerMeter;
            public int biClrUsed;
            public int biClrImportant;
        }
</pre></p>
<p>Utility class to convert structures to binary :</p>
<p><pre class="brush: csharp;">
    public static class BinaryStructConverter
    {
        public static T FromByteArray&lt;T&gt;(byte[] bytes) where T : struct
        {
            IntPtr ptr = IntPtr.Zero;
            try
            {
                int size = Marshal.SizeOf(typeof(T));
                ptr = Marshal.AllocHGlobal(size);
                Marshal.Copy(bytes, 0, ptr, size);
                object obj = Marshal.PtrToStructure(ptr, typeof(T));
                return (T)obj;
            }
            finally
            {
                if (ptr != IntPtr.Zero)
                    Marshal.FreeHGlobal(ptr);
            }
        }

        public static byte[] ToByteArray&lt;T&gt;(T obj) where T : struct
        {
            IntPtr ptr = IntPtr.Zero;
            try
            {
                int size = Marshal.SizeOf(typeof(T));
                ptr = Marshal.AllocHGlobal(size);
                Marshal.StructureToPtr(obj, ptr, true);
                byte[] bytes = new byte[size];
                Marshal.Copy(ptr, bytes, 0, size);
                return bytes;
            }
            finally
            {
                if (ptr != IntPtr.Zero)
                    Marshal.FreeHGlobal(ptr);
            }
        }
    }
</pre></p>
<p>The image returned by that code can be safely used in an <code>Image</code> control.</p>
<p>That goes to show that, even with a state-of-the-art technology like WPF, we still have to get our hands dirty sometimes <img src='http://s1.wp.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> . Let&#8217;s hope Microsoft will fix this in a later version&#8230;</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tomlev2.wordpress.com/21/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tomlev2.wordpress.com/21/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tomlev2.wordpress.com/21/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tomlev2.wordpress.com/21/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/tomlev2.wordpress.com/21/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/tomlev2.wordpress.com/21/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/tomlev2.wordpress.com/21/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/tomlev2.wordpress.com/21/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tomlev2.wordpress.com/21/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tomlev2.wordpress.com/21/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tomlev2.wordpress.com/21/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tomlev2.wordpress.com/21/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tomlev2.wordpress.com/21/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tomlev2.wordpress.com/21/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tomlev2.wordpress.com&amp;blog=7442815&amp;post=21&amp;subd=tomlev2&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://tomlev2.wordpress.com/2009/02/05/wpf-paste-an-image-from-the-clipboard/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f4acdb91aba11ddf8f03d4b12453f3d5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tomlev</media:title>
		</media:content>
	</item>
		<item>
		<title>[WPF] Binding to application settings using a markup extension</title>
		<link>http://tomlev2.wordpress.com/2008/11/18/wpf-binding-to-application-settings-using-a-markup-extension/</link>
		<comments>http://tomlev2.wordpress.com/2008/11/18/wpf-binding-to-application-settings-using-a-markup-extension/#comments</comments>
		<pubDate>Tue, 18 Nov 2008 13:56:48 +0000</pubDate>
		<dc:creator>Thomas Levesque</dc:creator>
				<category><![CDATA[Code sample]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[binding]]></category>
		<category><![CDATA[markup extension]]></category>
		<category><![CDATA[settings]]></category>
		<category><![CDATA[XAML]]></category>

		<guid isPermaLink="false">http://tomlev.wordpress.com/?p=3</guid>
		<description><![CDATA[Hi, this is my first post on this blog, I hope you will enjoy it . If you want to know a few things about me, please check out this page. The end-user of any application expects that his preferences (window size, state of this or that option&#8230;) are saved to be restored at the [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tomlev2.wordpress.com&amp;blog=7442815&amp;post=156&amp;subd=tomlev2&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Hi, this is my first post on this blog, I hope you will enjoy it <img src='http://s1.wp.com/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> . If you want to know a few things about me, please check out <a href="http://tomlev2.wordpress.com/about/">this page</a>.</p>
<p>The end-user of any application expects that his preferences (window size, state of this or that option&#8230;) are saved to be restored at the next run : that&#8217;s why .NET 2.0 introduced application settings as a unified way to persist these settings. However, if there are many settings, it can be a real hassle for the developper to handle them&#8230; even with the help of the Settings class generated by Visual Studio, there is still quite a lot of code to write to apply these settings to the user interface, then update them according to user modifications.</p>
<p>In Windows Forms, it was possible to define bindings between control properties and application settings, but it wasn&#8217;t very intuitive, and wasn&#8217;t very widely used (I&#8217;m not so sure about that, but I actually never saw it used by anyone&#8230;).</p>
<p>With WPF, we can do something similar in a much more elegant way&#8230; although it&#8217;s not &#8220;officially&#8221; documented, it is possible to create bindings to application settings in XAML. For instance, to persist the window size and position in application settings, many blogs suggest this approach :</p>
<p><pre class="brush: xml;">
&lt;Window x:Class=&quot;WpfApplication1.Window1&quot;
        xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
        xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
        xmlns:p=&quot;clr-namespace:WpfApplication1.Properties&quot;
        Title=&quot;Window1&quot;
        Height=&quot;{Binding Source={x:Static p:Settings.Default}, Path=Height, Mode=TwoWay}&quot;
        Width=&quot;{Binding Source={x:Static p:Settings.Default}, Path=Width, Mode=TwoWay}&quot;
        Left=&quot;{Binding Source={x:Static p:Settings.Default}, Path=Left, Mode=TwoWay}&quot;
        Top=&quot;{Binding Source={x:Static p:Settings.Default}, Path=Top, Mode=TwoWay}&quot;&gt;
</pre></p>
<p>(In that example, Height, Width, Top and Left are application settings)</p>
<p>This code does work, but honestly, do you feel like writing this for every setting of the application ? It&#8217;s too verbose, not intuitive, and makes the code harder to read&#8230;</p>
<p>Of course, I&#8217;m not saying this idea is bad… but it&#8217;s very easy to improve it, by creating our own « markup extension ». In this post I&#8217;m going to explain how to write a class that inherits Binding, and allows to bind easily to application settings.</p>
<p>« Markup extension » are objects that can be used in XAML to retrieve values. They are used all the time in WPF : for instance, Binding, StaticResource and DynamicResource are markup extensions.</p>
<p>It&#8217;s quite easy to define your own markup extension, by creating a class that inherits the abstract MarkupExtension class, and implements the ProvideValue method. In our case, most of what we need is already implemented in the Binding class (which indirectly inherits MarkupExtension). So we&#8217;re just going to inherit Binding, and initialize the necessary properties in order to bind to application settings :</p>
<p><pre class="brush: csharp;">
using System.Windows.Data;

namespace WpfApplication1
{
    public class SettingBindingExtension : Binding
    {
        public SettingBindingExtension()
        {
            Initialize();
        }

        public SettingBindingExtension(string path)
            :base(path)
        {
            Initialize();
        }

        private void Initialize()
        {
            this.Source = WpfApplication1.Properties.Settings.Default;
            this.Mode = BindingMode.TwoWay;
        }
    }
}
</pre></p>
<p>Note the « Extension » suffix at the end of the class name : by convention, most markup extensions have this suffix (Binding is an exception…). It can be omitted when using the class in XAML (similarly to attributes, for which the « Attribute » suffix can be omitted).</p>
<p>In that class, we defined two constructors, matching those of the Binding class. We don&#8217;t need to redefine the ProvideValue method, because the one implemented in the Binding class suits us perfectly (and anyway it is marked as sealed, so we couldn&#8217;t override it even if we wanted to&#8230;). The part that actually makes the code work is the Initialize method. It initializes the Source property, so that the Path of the binding maps to the specified setting, and sets Mode to TwoWay so that application settings are automatically updated from the UI. The point of doing this is that we don&#8217;t have to set these properties every time we bind to a setting&#8230;</p>
<p>To illustrate the usage of this markup extension, let&#8217;s go back to the previous example, and replace the Bindings with the SettingBinding extension :</p>
<p><pre class="brush: xml;">
&lt;Window x:Class=&quot;WpfApplication1.Window1&quot;
        xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
        xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
        xmlns:my=&quot;clr-namespace:WpfApplication1&quot;
        Title=&quot;Window1&quot;
        Height=&quot;{my:SettingBinding Height}&quot;
        Width=&quot;{my:SettingBinding Width}&quot;
        Left=&quot;{my:SettingBinding Left}&quot;
        Top=&quot;{my:SettingBinding Top}&quot;&gt;
</pre></p>
<p>Isn&#8217;t it much clearer, more readable, and shorter to write ?</p>
<p>And of course, to make it work, let&#8217;s not forget to save the settings in the application&#8217;s Exit event…</p>
<p><pre class="brush: csharp;">
        private void Application_Exit(object sender, ExitEventArgs e)
        {
            WpfApplication1.Properties.Settings.Default.Save();
        }
</pre></p>
<p>That&#8217;s it ! the window size and position are now saved, and restored when the application is started again, without having to write anything more&#8230;</p>
<p><a href='http://tlevesque.developpez.com/files/SettingBindingSample.zip'>Download source code</a></p>
<p><strong>Update :</strong> If you understand French and want to know more about markup extensions, I suggest you read my tutorial on this topic : <a href="http://tlevesque.developpez.com/dotnet/wpf-markup-extensions/">Les markup extensions en WPF</a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tomlev2.wordpress.com/156/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tomlev2.wordpress.com/156/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tomlev2.wordpress.com/156/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tomlev2.wordpress.com/156/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/tomlev2.wordpress.com/156/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/tomlev2.wordpress.com/156/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/tomlev2.wordpress.com/156/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/tomlev2.wordpress.com/156/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tomlev2.wordpress.com/156/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tomlev2.wordpress.com/156/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tomlev2.wordpress.com/156/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tomlev2.wordpress.com/156/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tomlev2.wordpress.com/156/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tomlev2.wordpress.com/156/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tomlev2.wordpress.com&amp;blog=7442815&amp;post=156&amp;subd=tomlev2&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://tomlev2.wordpress.com/2008/11/18/wpf-binding-to-application-settings-using-a-markup-extension/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f4acdb91aba11ddf8f03d4b12453f3d5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tomlev</media:title>
		</media:content>
	</item>
	</channel>
</rss>
