<?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>Life, code and everything</title>
	<atom:link href="http://blog.elgaard.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.elgaard.com</link>
	<description>On life, universe and software development with focus on simplicity, quality and maintainability</description>
	<lastBuildDate>Fri, 07 Oct 2011 14:56:04 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='blog.elgaard.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Life, code and everything</title>
		<link>http://blog.elgaard.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://blog.elgaard.com/osd.xml" title="Life, code and everything" />
	<atom:link rel='hub' href='http://blog.elgaard.com/?pushpress=hub'/>
		<item>
		<title>Multiple Asserts in a Single Unit Test method</title>
		<link>http://blog.elgaard.com/2011/02/06/multiple-asserts-in-a-single-unit-test-method/</link>
		<comments>http://blog.elgaard.com/2011/02/06/multiple-asserts-in-a-single-unit-test-method/#comments</comments>
		<pubDate>Sat, 05 Feb 2011 22:07:00 +0000</pubDate>
		<dc:creator>Brian Elgaard</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Code]]></category>

		<guid isPermaLink="false">http://blog.elgaard.com/2011/02/05/multiple-asserts-in-a-single-unit-test-method/</guid>
		<description><![CDATA[The title of this post is a provocation to many people who have read and love Roy Osherove&#8217;s brilliant book, The Art of Unit Testing. In this book Roy clearly states that one of the pillars of good tests is to avoid multiple asserts in a unit test. The arguments against multiple asserts are multiple, [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.elgaard.com&amp;blog=9204421&amp;post=46&amp;subd=belgaard&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>The title of this post is a provocation to many people who have read and love <a href="http://www.manning.com/osherove/">Roy Osherove&#8217;s brilliant book, The Art of Unit Testing</a>. In this book Roy clearly states that one of the pillars of good tests is to avoid multiple asserts in a unit test.</p>
<p>The arguments against multiple asserts are multiple, a main one being that if one assert fails the rest will not be executed, which means that the state of the code under unit test is really unknown. Another argument is that if you find a need for having multiple asserts, it is probably because you are testing multiple things in a single unit test method. This will break the principle of <em>single responsibility</em> and maintainability will suffer.</p>
<p>I am a great believer in having maintainable and readable unit tests and I have always tried to follow the single assert advise myself. I am also a great believer in the principle of <em>single responsibility</em>, although I am often forced to be pragmatic when working on legacy code. When I want to test several outcomes from a single object I can choose to implement Equals, or maybe ToString in order to do direct comparisons of whole objects. Sometimes I will try to make a utility method or class that will allow me to compare several values in a way that will fit a single assert. While some people do not like adding to the code base for unit testing purposes only, most people object to having too many utilities creeping up in the unit test projects.</p>
<p>Recently I had discussions on unit testing with my colleagues and the reasoning behind single asserts came up – and also some arguments <em>against</em> it.</p>
<p>Let&#8217;s have a look at one of Roy&#8217;s examples,</p>
<pre class="code">[<span style="color:#2b91af;">TestMethod</span>]
<span style="color:blue;">public void </span>CheckVariousSumResults()
{
    <span style="color:#2b91af;">Assert</span>.AreEqual(3, <span style="color:blue;">this</span>.Sum(1001, 1, 2));
    <span style="color:#2b91af;">Assert</span>.AreEqual(3, <span style="color:blue;">this</span>.Sum(1, 1001, 2));
    <span style="color:#2b91af;">Assert</span>.AreEqual(3, <span style="color:blue;">this</span>.Sum(1, 2, 1001));
}</pre>
<p>The problem here is that if one assertion fails, the rest will not be run and we do not know if they would fail if run.</p>
<p>There are a number of solutions to this.</p>
<h2><font size="2">The first solution: Create a separate test for each assert </font></h2>
<p>This is easy and it only takes a few seconds to write those unit tests,</p>
<pre class="code">[<span style="color:#2b91af;">TestMethod</span>]
<span style="color:blue;">public void </span>Sum_1001AsFirstParam_Returns3()
{
    <span style="color:#2b91af;">Assert</span>.AreEqual(3, <span style="color:blue;">this</span>.Sum(1001, 1, 2));
}
[<span style="color:#2b91af;">TestMethod</span>]
<span style="color:blue;">public void </span>Sum_1001AsMiddleParam_Returns3()
{
    <span style="color:#2b91af;">Assert</span>.AreEqual(3, <span style="color:blue;">this</span>.Sum(1, 1001, 2));
}
[<span style="color:#2b91af;">TestMethod</span>]
<span style="color:blue;">public void </span>Sum_1001AsThirdParam_Returns3()
{
    <span style="color:#2b91af;">Assert</span>.AreEqual(3, <span style="color:blue;">this</span>.Sum(1, 2, 1001));
}</pre>
<p>What is the problem with this solution? </p>
<p>Well, although the example may be slightly contrived it is easy to imagine that the three cases are somewhat correlated. By putting all three asserts in a single method we have signaled that these must be considered as a whole in order to be understood, while if we create separate unit test we have lost this information. And imagine that there were more than three cases, say 42? If a fundamental bug in the Sum method creeps in so that all 42 unit tests fail, would you prefer to have 42 unit tests fail or would you prefer to have a single unit test fail?</p>
<p>Another problem is maintainability. It is correct that it only takes a few seconds to write these three unit tests, but someone needs to maintain them in all future and the task can become daunting due to the sheer number of unit tests.</p>
<p>Both problems can to a certain extend be overcome with proper naming and with true single responsibility of units under test as well as each unit test method, but that is not always the reality – especially when you try to put legacy code under unit test.</p>
<h2><font size="2">The Second Solution: Use Parameterized Tests</font> </p>
<p></h2>
<p>In many cases I would prefer to use parameterized tests. However, currently my unit testing environment is Visual Studio 2010 and it does not support such a feature!</p>
<h2><font size="2">The Third Solution: Use try-catch</font> </p>
<p></h2>
<p>Since an assertion failure means that an exception is thrown, at least in the unit test frameworks I have used so far, we can simply catch such exceptions, do some intelligent processing, and then allow the next assertion to fail or succeed. That solves our problem with having multiple asserts.</p>
<p>Even though Roy is my unit testing hero, I think he is a bit too hasty to simply abandon the try-catch solution with a statement like &quot;Some people think it&#8217;s a good idea to use a try-catch block [...] I think using parameterized tests is a far better way of achieving the same thing.&quot;</p>
<h2><font size="2">A Simple Solution Using try-catch</font> </p>
<p></h2>
<p>Since I cannot write parameterized unit tests with my unit testing environment, I had to come up with an alternative solution. My solution is to introduce a new MultiAssert class which will accept delegates to multiple assert statements but only fail at most once. This new class seems to be a logical addition to the existing family of assert classes along with e.g. CollectionAssert and StringAssert.</p>
<p>Here is the above example in a single unit test with a single assertion,</p>
<pre class="code">[<span style="color:#2b91af;">TestMethod</span>]
<span style="color:blue;">public void </span>CheckVariousSumResults()
{
    <span style="color:#2b91af;">MultiAssert</span>.Aggregate(
        () =&gt; <span style="color:#2b91af;">Assert</span>.AreEqual(3, <span style="color:blue;">this</span>.Sum(1001, 1, 2)),
        () =&gt; <span style="color:#2b91af;">Assert</span>.AreEqual(3, <span style="color:blue;">this</span>.Sum(1, 1001, 2)),
        () =&gt; <span style="color:#2b91af;">Assert</span>.AreEqual(3, <span style="color:blue;">this</span>.Sum(1, 2, 1001)));
}</pre>
<p>MultiAssert.Aggregate can even be used in situations that do not fit parameterized unit tests easily.</p>
<p>Here is the implementation of MultiAssert.</p>
<pre class="code"><span style="color:blue;"><span style="color:blue;">public </span>static class </span><span style="color:#2b91af;">MultiAssert
</span>{
    <span style="color:blue;">public static void </span>Aggregate(<span style="color:blue;">params </span><span style="color:#2b91af;">Action</span>[] actions)
    {
        <span style="color:blue;">var </span>exceptions = <span style="color:blue;">new </span><span style="color:#2b91af;">List</span>&lt;<span style="color:#2b91af;">AssertFailedException</span>&gt;();

        <span style="color:blue;">foreach </span>(<span style="color:blue;">var </span>action <span style="color:blue;">in </span>actions)
        {
            <span style="color:blue;">try
            </span>{
                action();
            }
            <span style="color:blue;">catch </span>(<span style="color:#2b91af;">AssertFailedException </span>ex)
            {
                exceptions.Add(ex);
            }
        }

        <span style="color:blue;">var </span>assertionTexts =
            exceptions.Select(assertFailedException =&gt; assertFailedException.Message);
        <span style="color:blue;">if </span>(0 != assertionTexts.Count())
        {
            <span style="color:blue;">throw new
                </span><span style="color:#2b91af;">AssertFailedException</span>(
                assertionTexts.Aggregate(
                    (aggregatedMessage, next) =&gt; aggregatedMessage + <span style="color:#2b91af;">Environment</span>.NewLine + next));
        }
    }
}</pre>
<h2><font size="2">Using or Abusing Multiple Asserts</font> </p>
<p></h2>
<p>MultiAssert can be abused, it is not meant as a universal excuse for cramming a lot of assertions into any unit test method. Remember that maintainability and readability of unit tests must still be a top priority and you should only use MultiAssert when this can be achieved.</p>
<p>One situation in which I recommend the use of MultiAssert is when it makes sense to assert both pre- and post-conditions in a unit test method. In this context, a post-condition is simply a (single) assert that states something about the state of the world after the <em>Act</em> part of the unit test method. However, if you assert that something has the value 42, how do you know that this was not already true right after the <em>Arrange</em> part of the unit test? After all, the <em>Assert</em> part of your unit test must assert what was supposed to happen as a consequence of the <em>Act</em> part of the unit test method.</p>
<p>So one nice usage of MultiAssert is to assert both pre- and post-conditions in unit tests.</p>
<pre>
<pre class="code">[<span style="color:#2b91af;">TestMethod</span>]
<span style="color:blue;">public void </span>Foo()
{
    <span style="color:green;">// Arrange
    </span><span style="color:blue;">var </span>underTest = <span style="color:blue;">…</span>;
    <span style="color:blue;">bool </span>preCondition = underTest.TheFoo() != 42;

    <span style="color:green;">// Act
    </span>underTest.Foo();
    <span style="color:blue;">int </span>actual = underTest.TheFoo();

    <span style="color:green;">// Assert
    </span><span style="color:#2b91af;">MultiAssert</span>.Aggregate(
        () =&gt; <span style="color:#2b91af;">Assert</span>.IsTrue(preCondition),
        () =&gt; <span style="color:#2b91af;">Assert</span>.AreEqual(42, actual));
}
</pre>
</pre>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/belgaard.wordpress.com/46/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/belgaard.wordpress.com/46/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/belgaard.wordpress.com/46/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/belgaard.wordpress.com/46/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/belgaard.wordpress.com/46/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/belgaard.wordpress.com/46/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/belgaard.wordpress.com/46/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/belgaard.wordpress.com/46/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/belgaard.wordpress.com/46/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/belgaard.wordpress.com/46/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/belgaard.wordpress.com/46/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/belgaard.wordpress.com/46/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/belgaard.wordpress.com/46/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/belgaard.wordpress.com/46/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.elgaard.com&amp;blog=9204421&amp;post=46&amp;subd=belgaard&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.elgaard.com/2011/02/06/multiple-asserts-in-a-single-unit-test-method/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/da973d0ef671850a3376f87377168f3a?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">belgaard</media:title>
		</media:content>
	</item>
		<item>
		<title>Setting the Windows Phone 7 SMTP Port</title>
		<link>http://blog.elgaard.com/2011/01/01/setting-the-windows-phone-7-smtp-port/</link>
		<comments>http://blog.elgaard.com/2011/01/01/setting-the-windows-phone-7-smtp-port/#comments</comments>
		<pubDate>Sat, 01 Jan 2011 13:12:00 +0000</pubDate>
		<dc:creator>Brian Elgaard</dc:creator>
				<category><![CDATA[Everything]]></category>
		<category><![CDATA[SilverLight]]></category>

		<guid isPermaLink="false">https://belgaard.wordpress.com/2011/01/01/setting-the-windows-phone-7-smtp-port/</guid>
		<description><![CDATA[I am now the happy owner of a Windows Phone 7 device, Samsung’s Omnia 7. I am a happy user of Samsung’s hardware as well as Microsoft’s software, including the new Metro user interface, My Phone’s ability to locate my phone, the Zune software etc. And I am thrilled about the developer story – that [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.elgaard.com&amp;blog=9204421&amp;post=44&amp;subd=belgaard&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I am now the happy owner of a Windows Phone 7 device, Samsung’s Omnia 7.</p>
<p>I am a happy user of Samsung’s hardware as well as Microsoft’s software, including the new Metro user interface, My Phone’s ability to locate my phone, the Zune software etc. And I am thrilled about the developer story – that apps can be developed using Silverlight and C# with Visual Studio and other familiar tools.</p>
<p>I intend to blog about developing apps as soon as I get proper hands-on experience.</p>
<p>One end-user problem struck me immediately when I tried to setup the phone. I use a hosted email solution which I can use to read my email through POP3/IMAP and I can send email through SMTP, all of which WP7 supports nicely.</p>
<p>Well, except that there seems to be no way to specify the SMTP port to be used, which is odd since it is quite common to have the default port 25 blocked?</p>
<p>As usual, there is a simple solution to this problem – simply specify the port after the SMTP server name. For example, if the server name is ‘myServer.com’ and the port to use is 42, specify this as ‘myServer.com:42:0’.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/belgaard.wordpress.com/44/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/belgaard.wordpress.com/44/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/belgaard.wordpress.com/44/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/belgaard.wordpress.com/44/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/belgaard.wordpress.com/44/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/belgaard.wordpress.com/44/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/belgaard.wordpress.com/44/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/belgaard.wordpress.com/44/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/belgaard.wordpress.com/44/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/belgaard.wordpress.com/44/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/belgaard.wordpress.com/44/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/belgaard.wordpress.com/44/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/belgaard.wordpress.com/44/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/belgaard.wordpress.com/44/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.elgaard.com&amp;blog=9204421&amp;post=44&amp;subd=belgaard&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.elgaard.com/2011/01/01/setting-the-windows-phone-7-smtp-port/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/da973d0ef671850a3376f87377168f3a?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">belgaard</media:title>
		</media:content>
	</item>
		<item>
		<title>The Silverlight 3 SelectedIndex bug</title>
		<link>http://blog.elgaard.com/2010/01/05/the-silverlight-3-selectedindex-bug/</link>
		<comments>http://blog.elgaard.com/2010/01/05/the-silverlight-3-selectedindex-bug/#comments</comments>
		<pubDate>Tue, 05 Jan 2010 19:17:06 +0000</pubDate>
		<dc:creator>Brian Elgaard</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[SilverLight]]></category>

		<guid isPermaLink="false">http://belgaard.wordpress.com/2010/01/05/the-silverlight-3-selectedindex-bug/</guid>
		<description><![CDATA[There is a Silverlight bug which bothers a lot of users worldwide – if you bing the issue you will find quite a few hits. The Problem The problem is simple to state. Create a combo box and bind to the SelectedIndex and ItemsSource properties and you get an out of bounds error when a [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.elgaard.com&amp;blog=9204421&amp;post=36&amp;subd=belgaard&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>There is a Silverlight bug which bothers a lot of users worldwide – if you bing the issue you will find quite a few hits.</p>
<h4>The Problem</h4>
<p>The problem is simple to state. Create a combo box and bind to the SelectedIndex and ItemsSource properties and you get an out of bounds error when a value is selected.</p>
<pre class="code"><span style="color:blue;">&lt;</span><span style="color:#a31515;">ComboBox </span><span style="color:red;">SelectedIndex</span><span style="color:blue;">="{</span><span style="color:#a31515;">Binding </span><span style="color:red;">Path</span><span style="color:blue;">=IndexOfCurrentValue}" </span><span style="color:red;">ItemsSource</span><span style="color:blue;">="{</span><span style="color:#a31515;">Binding </span><span style="color:red;">Values</span><span style="color:blue;">}"</span><span style="color:blue;">&gt;</span></pre>
<p>One of the sources that describe the problem is <a href="http://www.lhotka.net/weblog/SilverlightComboBoxControlAndDataBinding.aspx">http://www.lhotka.net/weblog/SilverlightComboBoxControlAndDataBinding.aspx</a>. This post includes a work around but I wanted to find a simpler solution.</p>
<p>I asked the Silverlight product team and the answer was that this bug is very unfortunate, but that it may not be trivial to fix.</p>
<p>In my repro project, I bound SelectedIndex before binding ItemsSource, so when the binding engine sets the SelectedIndex property, items are not set yet and the value 0 is not correct.</p>
<h4>The Solution</h4>
<p>The workaround is simple; simply switch the order of bindings in XAML and bind ItemsSource before binding SelectedIndex.</p>
<p>This is a reported bug and it is still open at the time of writing this. I hope it will be fixed by Silverlight 4.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/belgaard.wordpress.com/36/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/belgaard.wordpress.com/36/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/belgaard.wordpress.com/36/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/belgaard.wordpress.com/36/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/belgaard.wordpress.com/36/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/belgaard.wordpress.com/36/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/belgaard.wordpress.com/36/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/belgaard.wordpress.com/36/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/belgaard.wordpress.com/36/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/belgaard.wordpress.com/36/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/belgaard.wordpress.com/36/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/belgaard.wordpress.com/36/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/belgaard.wordpress.com/36/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/belgaard.wordpress.com/36/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.elgaard.com&amp;blog=9204421&amp;post=36&amp;subd=belgaard&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.elgaard.com/2010/01/05/the-silverlight-3-selectedindex-bug/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/da973d0ef671850a3376f87377168f3a?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">belgaard</media:title>
		</media:content>
	</item>
		<item>
		<title>Silverlight and WPF Single-Sourcing &#8211; XAML namespaces</title>
		<link>http://blog.elgaard.com/2009/11/25/silverlight-and-wpf-single-sourcing-%e2%80%93-xaml-namespaces/</link>
		<comments>http://blog.elgaard.com/2009/11/25/silverlight-and-wpf-single-sourcing-%e2%80%93-xaml-namespaces/#comments</comments>
		<pubDate>Wed, 25 Nov 2009 21:06:19 +0000</pubDate>
		<dc:creator>Brian Elgaard</dc:creator>
				<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://blog.elgaard.com/2009/11/25/silverlight-and-wpf-single-sourcing-%e2%80%93-xaml-namespaces/</guid>
		<description><![CDATA[I have found that WPF and Silverlight XAML are sufficiently different to make single-sourcing difficult. At first I did not know if it was possible at all, but I knew one thing – the differences in usage of namespaces look like something very annoying for which there must be an elegant solution. The Problem The [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.elgaard.com&amp;blog=9204421&amp;post=32&amp;subd=belgaard&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I have found that WPF and Silverlight XAML are sufficiently different to make single-sourcing difficult.</p>
<p>At first I did not know if it was possible at all, but I knew one thing – the differences in usage of namespaces look like something very annoying for which there must be an elegant solution.</p>
<h4>The Problem   <br /></h4>
<p>The first issue was with the standard controls which are in WPF 4.0 but <em>not</em> in Silverlight 3.0 (only in the <a href="http://www.codeplex.com/Wiki/View.aspx?ProjectName=Silverlight">toolkit</a>), e.g. the Expander is declared like this in WPF,</p>
<p><span style="font-family:courier new;font-size:10pt;"><span style="color:blue;">&lt;</span><span style="color:#a31515;">Expander</span><span style="color:red;"> … /</span><span style="color:blue;">&gt;</span></span></p>
<p>But it is declared like this in Silverlight,</p>
<p><span style="font-family:courier new;font-size:10pt;"><span style="color:red;">… xmlns</span><span style="color:blue;">:</span><span style="color:red;">Controls1</span><span style="color:blue;">=&quot;clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Toolkit&quot; …       <br />&lt;</span><span style="color:#a31515;">Controls1</span><span style="color:blue;">:</span><span style="color:#a31515;">Expander</span><span style="color:red;"> … /</span><span style="color:blue;">&gt;       <br /></span></span></p>
<p>What I really did not understand was that there is a similar problem when the standard controls which are in WPF 4.0 <em>also are</em> in Silverlight 3.0; for example, the <span style="font-family:courier new;color:#a31515;font-size:10pt;">HierarchicalDataTemplate</span> is declared like this in WPF,</p>
<p><span style="font-family:courier new;font-size:10pt;"><span style="color:blue;">&lt;</span><span style="color:#a31515;">HierarchicalDataTemplate … /&gt;</span></span></p>
<p>But it is declared like this in Silverlight,</p>
<p><span style="font-family:courier new;font-size:10pt;"><span style="color:red;">… xmlns</span><span style="color:blue;">:</span><span style="color:red;">Windows</span><span style="color:blue;">=&quot;clr-namespace:System.Windows;assembly=System.Windows.Controls&quot; …       <br />&lt;</span><span style="color:#a31515;">Windows</span><span style="color:blue;">:</span><span style="color:#a31515;">HierarchicalDataTemplate … /&gt;       <br /></span></span></p>
<p>Clearly the rules for defaulting and declaring namespaces are different.</p>
<h4>The First Solution   <br /></h4>
<p>I searched the Internet and found a few suggestions. One suggestion is to have two sets of name space references. This works because you are allowed to use name spaces on WPF although it is not mandatory. I did not like it because it still meant maintaining different files since XAML does not allow #IFDEF-like constructs.</p>
<p>My colleague David Anson found a surprisingly simple solution which he describes in a <a href="http://blogs.msdn.com/delay/archive/2009/10/21/two-birds-one-stone-silverlight-wpf-data-visualization-development-release-2-and-datavisualizationdemos-update.aspx">blog</a> post (see the last bullet in the notes at the end of the post). The main idea is to subclass standard controls, effectively bringing them into the same namespace across Silverlight and WPF.</p>
<p>It looks like magic – and <a href="http://www.jetbrains.com/resharper/">ReSharper</a> also claims that this is not valid – but it works. Well, it almost works.</p>
<h4>The Problem with the First Solution   <br /></h4>
<p>So far I have found one problem with the first solution – the <span style="font-family:courier new;color:#a31515;font-size:10pt;">HierarchicalDataTemplate</span><span style="color:#1f497d;">.     <br /></span></p>
<p>If I used David&#8217;s trick,</p>
<p><span style="font-family:courier new;font-size:10pt;"><span style="color:blue;">public </span><span style="color:blue;">class </span><span style="color:#2b91af;">HierarchicalDataTemplate</span> : System.Windows.<span style="color:#2b91af;">HierarchicalDataTemplate</span> { }      <br /></span></p>
<p><span style="font-family:courier new;font-size:10pt;"><span style="color:red;">xmlns</span><span style="color:blue;">:</span><span style="color:red;">Std</span><span style="color:blue;">=&quot;clr-namespace:Microsoft.Dynamics.Ax.Frameworks.Controls.StandardControls&quot;</span></span><span style="color:#1f497d;">     <br /></span></p>
<p><span style="font-family:courier new;font-size:10pt;"><span style="color:blue;">41: &lt;</span><span style="color:#a31515;">Std</span><span style="color:blue;">:</span><span style="color:#a31515;">HierarchicalDataTemplate</span><span style="color:red;"> x</span><span style="color:blue;">:</span><span style="color:red;">Key</span><span style="color:blue;">=&quot;hierarchicalDataTemplate&quot;</span><span style="color:red;"> ItemsSource</span><span style="color:blue;">=&quot;{</span><span style="color:#a31515;">Binding</span><span style="color:red;"> Path</span><span style="color:blue;">=Subcomponents}&quot;&gt;       <br /></span><span style="color:#a31515;">42:&#160;&#160;&#160; </span><span style="color:blue;">&lt;</span><span style="color:#a31515;">StackPanel</span><span style="color:red;"> Orientation</span><span style="color:blue;">=&quot;Horizontal&quot;&gt;       <br />43:&#160;&#160;&#160;&#160;&#160;&#160;&#160; &lt;</span><span style="color:#a31515;">Image</span><span style="color:red;"> Source</span><span style="color:blue;">=&quot;{</span><span style="color:#a31515;">Binding</span><span style="color:red;"> Path</span><span style="color:blue;">=TreeIcon}&quot;/&gt;       <br /></span><span style="color:#a31515;">44:&#160;&#160;&#160;&#160;&#160;&#160;&#160; </span><span style="color:blue;">&lt;</span><span style="color:#a31515;">TextBlock</span><span style="color:red;"> Text</span><span style="color:blue;">=&quot;{</span><span style="color:#a31515;">Binding</span><span style="color:red;"> Path</span><span style="color:blue;">=Name}&quot;/&gt;       <br /></span><span style="color:#a31515;">45:&#160;&#160;&#160; </span><span style="color:blue;">&lt;/</span><span style="color:#a31515;">StackPanel</span><span style="color:blue;">&gt;       <br />46: &lt;/</span><span style="color:#a31515;">Std</span><span style="color:blue;">:</span><span style="color:#a31515;">HierarchicalDataTemplate</span><span style="color:blue;">&gt;       <br /></span></span></p>
<p>Then it compiled in Silverlight and WPF but the <span style="font-family:courier new;color:#a31515;font-size:10pt;">StackPanel</span> caused problems at run-time in WPF. The error was</p>
<blockquote><p>&#8216;StackPanel&#8217; object cannot be added to &#8216;HierarchicalDataTemplate&#8217;. Object of type &#8216;System.Windows.Controls.StackPanel&#8217; cannot be converted to type &#8216;System.Windows.FrameworkElementFactory&#8217;.&#160; Error at object &#8216;System.Windows.Controls.StackPanel&#8217; in markup file &#8216;Microsoft.Dynamics.Ax.Frameworks.Controls;component/singlesourcetest.xaml&#8217; Line 42 Position 26.</p>
</blockquote>
<p>It did not help to use David&#8217;s trick again and add <span style="font-family:courier new;color:#a31515;font-size:10pt;">StackPanel</span> to the <span style="font-family:courier new;color:#a31515;font-size:10pt;">Std</span> namespace.</p>
<p>This is a WPF bug. It has not been fixed in the WPF 4.0 beta I am using but I hope it will be fixed eventually in the RTM.</p>
<h4>The Second Solution   <br /></h4>
<p>David worked hard on this problem and got another brilliant idea; if this is a problem with WPF only then why not subclass in Silverlight only? This requires a little trick that left David &quot;a little slimy&quot; – see his <a href="http://blogs.msdn.com/delay/archive/2009/11/23/sharing-isn-t-easy-for-anyone-tricks-for-sharing-the-same-xaml-files-across-silverlight-and-wpf.aspx">blog post</a> for the details – but it works. Well, it almost works.</p>
<h4>The Problem with the Second Solution   <br /></h4>
<p>I took the sample project from the <a href="http://blogs.msdn.com/delay/archive/2009/11/23/sharing-isn-t-easy-for-anyone-tricks-for-sharing-the-same-xaml-files-across-silverlight-and-wpf.aspx">blog post</a> for a spin and found that it would not work if I added <span style="font-family:courier new;font-size:10pt;"><span style="color:red;">x</span><span style="color:blue;">:</span><span style="color:red;">Name</span><span style="color:blue;">=&quot;myTreeview</span></span>&quot; to the TreeView in XAML. This is the error I got,</p>
<blockquote><p>The type &#8216;System.Windows.Controls.TreeView&#8217; exists in both &#8216;c:\Program Files\Microsoft SDKs\Silverlight\v3.0\Libraries\Client\System.Windows.Controls.dll&#8217; and &#8216;e: \SharingXamlSilverlightWpf\PresentationFramework\Bin\Debug\PresentationFramework.dll&#8217;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; e:\enlistments\axmain6\source\frameworks\controls\sharingxamlsilverlightwpf\sharingxamlsilverlightwpf-sl\obj\debug\mainpage.g.cs&#160;&#160;&#160;&#160;&#160; 38&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; 42&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; SharingXamlSilverlightWpf-SL</p>
</blockquote>
<p>Clearly there is a problem with disambiguating identical names across assemblies.</p>
<p>I needed to reference the name of the tree from a details view so I could not use the second solution for at least the controls that I needed to name.</p>
<p>But since the second solution seemed to only be needed for <span style="font-family:courier new;color:#a31515;font-size:10pt;">HierarchicalDataTemplate</span> anyway, I am now using the first solution for everything but the <span style="font-family:courier new;color:#a31515;font-size:10pt;">HierarchicalDataTemplate</span>.</p>
<p>And this works. Well, it almost works. But the remaining problems seem to be unrelated to this single-sourcing approach so I will defer blogging about it till later.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/belgaard.wordpress.com/32/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/belgaard.wordpress.com/32/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/belgaard.wordpress.com/32/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/belgaard.wordpress.com/32/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/belgaard.wordpress.com/32/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/belgaard.wordpress.com/32/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/belgaard.wordpress.com/32/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/belgaard.wordpress.com/32/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/belgaard.wordpress.com/32/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/belgaard.wordpress.com/32/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/belgaard.wordpress.com/32/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/belgaard.wordpress.com/32/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/belgaard.wordpress.com/32/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/belgaard.wordpress.com/32/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.elgaard.com&amp;blog=9204421&amp;post=32&amp;subd=belgaard&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.elgaard.com/2009/11/25/silverlight-and-wpf-single-sourcing-%e2%80%93-xaml-namespaces/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/da973d0ef671850a3376f87377168f3a?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">belgaard</media:title>
		</media:content>
	</item>
		<item>
		<title>WPF: How to mark an input field as not valid</title>
		<link>http://blog.elgaard.com/2009/09/14/how-to-mark-an-input-field-as-not-valid/</link>
		<comments>http://blog.elgaard.com/2009/09/14/how-to-mark-an-input-field-as-not-valid/#comments</comments>
		<pubDate>Mon, 14 Sep 2009 20:14:41 +0000</pubDate>
		<dc:creator>Brian Elgaard</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://belgaard.wordpress.com/2009/09/14/how-to-mark-an-input-field-as-not-valid/</guid>
		<description><![CDATA[I wanted to add to my input controls a visual clue that tells if the current content of the control is valid. The visual clue I had in mind was a red squiggly line, similar to the way MS Word underlines my typos. Why this particular visual clue? Because this is how it is done [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.elgaard.com&amp;blog=9204421&amp;post=22&amp;subd=belgaard&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I wanted to add to my input controls a visual clue that tells if the current content of the control is valid.</p>
<p>The visual clue I had in mind was a red squiggly line, similar to the way MS Word underlines my typos.</p>
<p>Why this particular visual clue? Because this is how it is done in MS Dynamics AX,</p>
<p><a href="http://belgaard.files.wordpress.com/2009/09/clip_image0024.jpg"><img style="display:inline;border-width:0;" title="clip_image002[4]" border="0" alt="clip_image002[4]" src="http://belgaard.files.wordpress.com/2009/09/clip_image0024_thumb.jpg?w=193&#038;h=41" width="193" height="41"></a></p>
<p>This left me with two tasks,</p>
<p>1. How to trigger the actual validation.</p>
<p>2. How to change the default WPF visual clue (a red border around the control) to the desired red squiggly line.</p>
<h4>How to trigger validation</h4>
<p>I thought about using validation rules similar to what Nigel Spencer <a href="http://blog.spencen.com/2007/10/04/wpf-validation-rules.aspx">blogged</a> about. But validation is only triggered when the binding value has changed, while I wanted the visual clue to work even at start-up.</p>
<p>I was not alone with this problem. Willem Meints <a href="http://blogs.infosupport.com/blogs/willemm/archive/2008/04/12/Validation-framework-for-WPF.aspx">blogged</a> about this as well as about several other validation problems. He actually wrote a complete validation framework that I found would be too much of a good thing for me. He also wrote that he did not use <a href="http://blogs.msdn.com/wpfsdk/archive/2007/10/02/data-validation-in-3-5.aspx">IDataErrorInfo</a> as it does not provide enough flexibility. </p>
<p>I like to keep things simple, so I opted to use IDataErrorInfo.</p>
<p>Basically, I let the business object I bind to report an error if it is not happy about what the user typed so far. It can be augmented by validation rules, e.g. a user defined NumberRangeValue.</p>
<p>For the simple case, meaning the check for mandatory fields having a value, I use code similar to the following,</p>
<pre class="code"><span style="color:blue;">public string this[string columnName]
{
    get
    {
        if (string.IsNullOrEmpty(columnName))
        {
            return string.Empty;
        }

        if (&lt;this is a mandatory field and has no value&gt;)
        {
            </span><span style="color:green;">// This is never shown in the UI and does not
            // have to be localized; but if we ever choose
            // to show this text it must be localized!
            </span><span style="color:blue;">return </span><span style="color:#a31515;">"This field is mandatory.";
        }

        </span><span style="color:blue;">return string.Empty;
    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></span></p>
<p>Now I need to figure out how to trick the visual of controls to show a squiggly red line instead of the default red border.</p>
<h4>How to get the red squiggly line</h4>
<p>The TextBlock control can actually do the trick with the red squiggly line with its built-in spell checker. Alas, there is no API to trigger this at will.</p>
<p>Instead I found that the following XAML placed in a Resources section would do the trick,</p>
<pre class="code"><span style="color:blue;">&lt;</span><span style="color:#a31515;">DrawingBrush </span><span style="color:red;">x</span><span style="color:blue;">:</span><span style="color:red;">Key</span><span style="color:blue;">="squiggleBrush" </span><span style="color:red;">TileMode</span><span style="color:blue;">="Tile"
        </span><span style="color:red;">Viewbox</span><span style="color:blue;">="0,0,4,4" </span><span style="color:red;">ViewboxUnits</span><span style="color:blue;">="Absolute"
        </span><span style="color:red;">Viewport</span><span style="color:blue;">="0,0,4,4" </span><span style="color:red;">ViewportUnits</span><span style="color:blue;">="Absolute"&gt;
    &lt;</span><span style="color:#a31515;">DrawingBrush.Drawing</span><span style="color:blue;">&gt;
        &lt;</span><span style="color:#a31515;">GeometryDrawing </span><span style="color:red;">Geometry</span><span style="color:blue;">="M 0,2 L 1,1 3,3 4,2"&gt;
            &lt;</span><span style="color:#a31515;">GeometryDrawing.Pen</span><span style="color:blue;">&gt;
                &lt;</span><span style="color:#a31515;">Pen </span><span style="color:red;">Brush</span><span style="color:blue;">="Red" </span><span style="color:red;">Thickness</span><span style="color:blue;">="1"
                </span><span style="color:red;">StartLineCap</span><span style="color:blue;">="Square" </span><span style="color:red;">EndLineCap</span><span style="color:blue;">="Square"/&gt;
            &lt;/</span><span style="color:#a31515;">GeometryDrawing.Pen</span><span style="color:blue;">&gt;
        &lt;/</span><span style="color:#a31515;">GeometryDrawing</span><span style="color:blue;">&gt;
    &lt;/</span><span style="color:#a31515;">DrawingBrush.Drawing</span><span style="color:blue;">&gt;
&lt;/</span><span style="color:#a31515;">DrawingBrush</span><span style="color:blue;">&gt;
&lt;</span><span style="color:#a31515;">ControlTemplate </span><span style="color:red;">x</span><span style="color:blue;">:</span><span style="color:red;">Key</span><span style="color:blue;">="SquiggleError"&gt;
&lt;</span><span style="color:#a31515;">StackPanel </span><span style="color:red;">HorizontalAlignment</span><span style="color:blue;">="Center" </span><span style="color:red;">VerticalAlignment</span><span style="color:blue;">=
        "Center"&gt;
        &lt;</span><span style="color:#a31515;">AdornedElementPlaceholder</span><span style="color:blue;">/&gt;
        &lt;</span><span style="color:#a31515;">Rectangle </span><span style="color:red;">Height</span><span style="color:blue;">="4" </span><span style="color:red;">Fill</span><span style="color:blue;">=
            "{</span><span style="color:#a31515;">StaticResource </span><span style="color:red;">squiggleBrush</span><span style="color:blue;">}"/&gt;
    &lt;/</span><span style="color:#a31515;">StackPanel</span><span style="color:blue;">&gt;
&lt;/</span><span style="color:#a31515;">ControlTemplate</span><span style="color:blue;">&gt;</span></pre>
<div id="codeSnippetWrapper">For e.g. a combo box I apply this template as follows,</div>
<div><span style="color:blue;"></span>&nbsp;</div>
<div><span style="color:blue;">&lt;</span><span style="color:#a31515;">ComboBox </span><span style="color:red;">…</span><span style="color:blue;">&gt;<br />&nbsp;&nbsp;&nbsp; &lt;</span><span style="color:#a31515;">Validation.ErrorTemplate</span><span style="color:blue;">&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;</span><span style="color:#a31515;">DynamicResource </span><span style="color:red;">ResourceKey</span><span style="color:blue;">=&#8221;SquiggleError&#8221;/&gt; &lt;/</span><span style="color:#a31515;">Validation.ErrorTemplate</span><span style="color:blue;">&gt;<br />&lt;/</span><span style="color:#a31515;">ComboBox</span><span style="color:blue;">&gt;<br /></span></div>
<div>All this ensures that the red squiggly line is drawn when I want it, and it looks close enough to the real thing,</div>
<p><a href="http://belgaard.files.wordpress.com/2009/09/clip_image0044.jpg"><img style="display:inline;border-width:0;" title="clip_image004[4]" border="0" alt="clip_image004[4]" src="http://belgaard.files.wordpress.com/2009/09/clip_image0044_thumb.jpg?w=193&#038;h=53" width="193" height="53"></a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/belgaard.wordpress.com/22/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/belgaard.wordpress.com/22/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/belgaard.wordpress.com/22/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/belgaard.wordpress.com/22/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/belgaard.wordpress.com/22/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/belgaard.wordpress.com/22/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/belgaard.wordpress.com/22/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/belgaard.wordpress.com/22/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/belgaard.wordpress.com/22/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/belgaard.wordpress.com/22/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/belgaard.wordpress.com/22/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/belgaard.wordpress.com/22/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/belgaard.wordpress.com/22/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/belgaard.wordpress.com/22/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.elgaard.com&amp;blog=9204421&amp;post=22&amp;subd=belgaard&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.elgaard.com/2009/09/14/how-to-mark-an-input-field-as-not-valid/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/da973d0ef671850a3376f87377168f3a?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">belgaard</media:title>
		</media:content>

		<media:content url="http://belgaard.files.wordpress.com/2009/09/clip_image0024_thumb.jpg" medium="image">
			<media:title type="html">clip_image002[4]</media:title>
		</media:content>

		<media:content url="http://belgaard.files.wordpress.com/2009/09/clip_image0044_thumb.jpg" medium="image">
			<media:title type="html">clip_image004[4]</media:title>
		</media:content>
	</item>
		<item>
		<title>WPF: Making combo box items disabled &#8211; also when accessed using the keyboard</title>
		<link>http://blog.elgaard.com/2009/09/03/wpf-making-combo-box-items-disabled-also-when-accessed-using-the-keyboard/</link>
		<comments>http://blog.elgaard.com/2009/09/03/wpf-making-combo-box-items-disabled-also-when-accessed-using-the-keyboard/#comments</comments>
		<pubDate>Thu, 03 Sep 2009 09:39:05 +0000</pubDate>
		<dc:creator>Brian Elgaard</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://belgaard.wordpress.com/2009/09/03/wpf-making-combo-box-items-disabled-also-when-accessed-using-the-keyboard/</guid>
		<description><![CDATA[When I first embarked on WPF I ran into a number of small problems. Here is one of them. The problem I tried various ways to make my data bound combo box items disabled. I found that binding the ComboboxItem.IsEnabled to a property that indicates whether the item should be enabled did the trick. But [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.elgaard.com&amp;blog=9204421&amp;post=13&amp;subd=belgaard&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>When I first embarked on WPF I ran into a number of small problems. Here is one of them.</p>
<h4>The problem</h4>
<p>I tried various ways to make my data bound combo box items disabled. I found that binding the ComboboxItem.IsEnabled to a property that indicates whether the item should be enabled did the trick.</p>
<p>But this did not work when I selected items using the keyboard. I also tried to make these not focusable but with the same result.</p>
<p>What worked: Click the combo down with the mouse and see that items that must be disabled can in fact not be selected.</p>
<p>What not worked: Use tab and arrow down to select items. They are not disabled and I can select them just fine with keyboard keys. Funny enough, if I click the combo down with the mouse, then the items are in fact disabled and cannot be selected with the keyboard keys.</p>
<p>Here is the XAML (I set up the data, meaning the properties FieldDomainValues, IsSelectable and ValueAsString, in constructers in code-behind):</p>
<pre class="code"><span style="color:blue;">&lt;</span><span style="color:#a31515;">ComboBox </span><span style="color:red;">x</span><span style="color:blue;">:</span><span style="color:red;">Name</span><span style="color:blue;">=&quot;cmbx_test&quot; </span><span style="color:red;">ItemsSource</span><span style="color:blue;">=&quot;{</span><span style="color:#a31515;">Binding </span><span style="color:red;">Path</span><span style="color:blue;">=FieldDomainValues}&quot;&gt;
    &lt;</span><span style="color:#a31515;">ComboBox.ItemContainerStyle</span><span style="color:blue;">&gt;
        &lt;</span><span style="color:#a31515;">Style</span><span style="color:blue;">&gt;
            &lt;</span><span style="color:#a31515;">Style.Triggers</span><span style="color:blue;">&gt;
                &lt;</span><span style="color:#a31515;">DataTrigger </span><span style="color:red;">Binding </span><span style="color:blue;">=&quot;{</span><span style="color:#a31515;">Binding </span><span style="color:red;">IsSelectable</span><span style="color:blue;">}&quot; </span><span style="color:red;">Value</span><span style="color:blue;">=&quot;False&quot;&gt;
                    &lt;</span><span style="color:#a31515;">Setter </span><span style="color:red;">Property</span><span style="color:blue;">=&quot;ComboBoxItem.Focusable&quot; </span><span style="color:red;">Value</span><span style="color:blue;">=&quot;False&quot;/&gt;
                    &lt;</span><span style="color:#a31515;">Setter </span><span style="color:red;">Property</span><span style="color:blue;">=&quot;ComboBoxItem.IsEnabled&quot; </span><span style="color:red;">Value</span><span style="color:blue;">=&quot;False&quot;/&gt;
                &lt;/</span><span style="color:#a31515;">DataTrigger</span><span style="color:blue;">&gt;
            &lt;/</span><span style="color:#a31515;">Style.Triggers</span><span style="color:blue;">&gt;
        &lt;/</span><span style="color:#a31515;">Style</span><span style="color:blue;">&gt;
    &lt;/</span><span style="color:#a31515;">ComboBox.ItemContainerStyle</span><span style="color:blue;">&gt;
    &lt;</span><span style="color:#a31515;">ComboBox.ItemTemplate</span><span style="color:blue;">&gt;
        &lt;</span><span style="color:#a31515;">DataTemplate</span><span style="color:blue;">&gt;
            &lt;</span><span style="color:#a31515;">StackPanel </span><span style="color:red;">Orientation</span><span style="color:blue;">=&quot;Horizontal&quot;&gt;
                &lt;</span><span style="color:#a31515;">TextBlock </span><span style="color:red;">Text</span><span style="color:blue;">=&quot;{</span><span style="color:#a31515;">Binding </span><span style="color:red;">Path</span><span style="color:blue;">=ValueAsString }&quot;&gt;&lt;/</span><span style="color:#a31515;">TextBlock</span><span style="color:blue;">&gt;
            &lt;/</span><span style="color:#a31515;">StackPanel</span><span style="color:blue;">&gt;
        &lt;/</span><span style="color:#a31515;">DataTemplate</span><span style="color:blue;">&gt;
    &lt;/</span><span style="color:#a31515;">ComboBox.ItemTemplate</span><span style="color:blue;">&gt;
&lt;/</span><span style="color:#a31515;">ComboBox</span><span style="color:blue;">&gt;</span></pre>
<p><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a></p>
<p>What did I do wrong here?</p>
<h4>The workaround</h4>
<p>Before we dig into the core reason for this problem, let’s have a look at a simple work-around that Parag Bhand suggested,</p>
<p><em>We also faced similar issues while dealing with binding in combobox. Once we open the dropdown every thing works fine (even from keyboard) then onwards. I guess it has something to do with ItemsContainerGenerator because item containers are not generated until dropdown is opened at least once.</em></p>
<p><em>In fact if we open the drop down and close it again programmatically in window&#8217;s loaded event handler then also it works fine.</em></p>
<pre class="code">cmbx_test.IsDropDownOpen = <span style="color:blue;">true</span>;
cmbx_test.IsDropDownOpen = <span style="color:blue;">false</span>;</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>This is what I do now and it works.</p>
<h4>The explanation</h4>
<p><a href="http://blogs.msdn.com/dwayneneed/">Dwayne Need</a>, found the explanation,</p>
<p><em>ComboBox.SelectItemHelper has logic to determine if the item and its corresponding container allow selection. When there is no container, this logic always returns True. The containers (ComboBoxItems) aren’t created until the dropdown box is measured, which doesn’t happen until the user causes the dropdown to appear, typically by clicking on its down-arrow button.</em></p>
<p><em>If you followed that, it’ll be clear why the workaround works. It causes a measure on the dropdown, which generates the containers. After that, SelectItemHelper’s logic picks up the state the app has declared for the containers. It should also be clear why we don’t do that for you automatically – the workaround creates UI that is never displayed.</em></p>
<p><em>This looks like a scenario bug to me. While the technical details make sense, the end-to-end scenario is broken.</em></p>
<p><em>Please file a bug.</em></p>
<p>This has now been filed as a bug (<em>750993: Unable to disable combo-box items when selected with the keyboard</em>).</p>
<p>Unfortunately the fix for this bug will not make it into .NET 4.0 so we must try and get around with the workaround for now.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/belgaard.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/belgaard.wordpress.com/13/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/belgaard.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/belgaard.wordpress.com/13/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/belgaard.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/belgaard.wordpress.com/13/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/belgaard.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/belgaard.wordpress.com/13/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/belgaard.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/belgaard.wordpress.com/13/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/belgaard.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/belgaard.wordpress.com/13/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/belgaard.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/belgaard.wordpress.com/13/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.elgaard.com&amp;blog=9204421&amp;post=13&amp;subd=belgaard&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.elgaard.com/2009/09/03/wpf-making-combo-box-items-disabled-also-when-accessed-using-the-keyboard/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/da973d0ef671850a3376f87377168f3a?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">belgaard</media:title>
		</media:content>
	</item>
		<item>
		<title>Life, code and everything</title>
		<link>http://blog.elgaard.com/2009/08/28/life-code-and-everything/</link>
		<comments>http://blog.elgaard.com/2009/08/28/life-code-and-everything/#comments</comments>
		<pubDate>Fri, 28 Aug 2009 19:55:53 +0000</pubDate>
		<dc:creator>Brian Elgaard</dc:creator>
				<category><![CDATA[Everything]]></category>

		<guid isPermaLink="false">http://belgaard.wordpress.com/2009/08/28/life-code-and-everything/</guid>
		<description><![CDATA[I decided to give my blog the title Life, code and everything. Why? I did it for two reasons. Firstly, because I am a passionate software developer so I will mainly write about code; but I also have a life; and I tend to have opinions on my own so I refuse to restrict myself [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.elgaard.com&amp;blog=9204421&amp;post=3&amp;subd=belgaard&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p class="MsoNormal" style="margin:0 0 10pt;"><span lang="EN-US"><span style="font-size:small;"><span style="font-family:Calibri;">I decided to give my blog the title <em>Life, code and everything.</em></span></span></span></p>
<p class="MsoNormal" style="margin:0 0 10pt;"><span lang="EN-US"><span style="font-family:Calibri;font-size:small;">Why? I did it for two reasons.</span></span></p>
<p class="MsoNormal" style="margin:0 0 10pt;"><span lang="EN-US"><span style="font-family:Calibri;font-size:small;">Firstly, because I am a passionate software developer so I will mainly write about <em>code</em>; but I also have a <em>life</em>; and I tend to have opinions on my own so I refuse to restrict myself too narrowly, hence <em>everything</em>.</span></span></p>
<p class="MsoNormal" style="margin:0 0 10pt;"><span lang="EN-US"><span style="font-family:Calibri;font-size:small;">Secondly, because I found that <em>Life, universe and software development with focus on simplicity, quality and maintainability</em> was a bit too long, although it is more to the point of what I intend to write about.</span></span></p>
<p class="MsoNormal" style="margin:0 0 10pt;"><span lang="EN-US"><span style="font-family:Calibri;font-size:small;">Thirdly, because it is a reference to certain literature that has left a lasting impression on me.</span></span></p>
<p><span style="line-height:115%;font-family:&quot;font-size:11pt;" lang="EN-US">That was three reasons, not two? Well, how can a trilogy consist of more than three books?</span></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/belgaard.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/belgaard.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/belgaard.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/belgaard.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/belgaard.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/belgaard.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/belgaard.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/belgaard.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/belgaard.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/belgaard.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/belgaard.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/belgaard.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/belgaard.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/belgaard.wordpress.com/3/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.elgaard.com&amp;blog=9204421&amp;post=3&amp;subd=belgaard&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.elgaard.com/2009/08/28/life-code-and-everything/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/da973d0ef671850a3376f87377168f3a?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">belgaard</media:title>
		</media:content>
	</item>
	</channel>
</rss>
