<?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 &#187; C#</title>
	<atom:link href="http://blog.elgaard.com/category/c/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 &#187; C#</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 &#8230; <a href="http://blog.elgaard.com/2011/02/06/multiple-asserts-in-a-single-unit-test-method/">Continue reading <span class="meta-nav">&#8594;</span></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" />]]></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>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 &#8230; <a href="http://blog.elgaard.com/2009/09/14/how-to-mark-an-input-field-as-not-valid/">Continue reading <span class="meta-nav">&#8594;</span></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" />]]></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 &#8230; <a href="http://blog.elgaard.com/2009/09/03/wpf-making-combo-box-items-disabled-also-when-accessed-using-the-keyboard/">Continue reading <span class="meta-nav">&#8594;</span></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" />]]></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>
	</channel>
</rss>
