<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Reed Copsey, Jr. &#187; WPF</title>
	<atom:link href="http://reedcopsey.com/category/dotnet/wpf/feed/" rel="self" type="application/rss+xml" />
	<link>http://reedcopsey.com</link>
	<description>Thoughts on C#, WPF, .NET, and programming for Scientific Visualization</description>
	<lastBuildDate>Tue, 20 Jul 2010 01:19:28 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Attached Property port of my Window Close Behavior</title>
		<link>http://reedcopsey.com/2010/04/15/attached-property-port-of-my-window-close-behavior/</link>
		<comments>http://reedcopsey.com/2010/04/15/attached-property-port-of-my-window-close-behavior/#comments</comments>
		<pubDate>Thu, 15 Apr 2010 21:12:39 +0000</pubDate>
		<dc:creator>Reed</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://reedcopsey.com/2010/04/15/attached-property-port-of-my-window-close-behavior/</guid>
		<description><![CDATA[Nishant Sivakumar just posted a nice article on The Code Project.&#160; It is a port of the MVVM-friendly Blend Behavior I wrote about in a previous article to WPF using Attached Properties. While similar to the WindowCloseBehavior code I posted on the Expression Code Gallery, Nishant Sivakumar’s version works in WPF without taking a dependency [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://blog.voidnish.com/" target="_blank">Nishant Sivakumar</a> just posted a nice article on <a href="http://www.codeproject.com/" target="_blank">The Code Project</a>.&#160; It is a port of the MVVM-friendly Blend Behavior I wrote about in <a href="http://reedcopsey.com/2009/10/09/using-behaviors-to-allow-the-viewmodel-to-manage-view-lifetime-in-m-v-vm/" target="_blank">a previous article</a> to WPF using <a href="http://msdn.microsoft.com/en-us/library/ms749011.aspx" target="_blank">Attached Properties</a>.</p>
<p>While similar to the <a href="http://gallery.expression.microsoft.com/en-us/WindowCloseBehavior" target="_blank">WindowCloseBehavior code I posted on the Expression Code Gallery</a>, <a href="http://www.codeproject.com/KB/WPF/WindowClosingBehavior.aspx" target="_blank">Nishant Sivakumar’s version</a> works in WPF without taking a dependency on the Expression Blend SDK.</p>
<p>I highly recommend reading this article: <a href="http://www.codeproject.com/KB/WPF/WindowClosingBehavior.aspx" target="_blank">Handling a Window’s Closed and Closing Events in the View-Model</a>.&#160; It is a very nice alternative approach to this common problem in MVVM.</p>
]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2010/04/15/attached-property-port-of-my-window-close-behavior/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>MEF CompositionInitializer for WPF</title>
		<link>http://reedcopsey.com/2010/03/26/mef-compositioninitializer-for-wpf/</link>
		<comments>http://reedcopsey.com/2010/03/26/mef-compositioninitializer-for-wpf/#comments</comments>
		<pubDate>Fri, 26 Mar 2010 22:45:46 +0000</pubDate>
		<dc:creator>Reed</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[.NET 4]]></category>
		<category><![CDATA[C# 4]]></category>
		<category><![CDATA[MEF]]></category>

		<guid isPermaLink="false">http://reedcopsey.com/2010/03/26/mef-compositioninitializer-for-wpf/</guid>
		<description><![CDATA[The Managed Extensibility Framework is an amazingly useful addition to the .NET Framework.  I was very excited to see System.ComponentModel.Composition added to the core framework.  Personally, I feel that MEF is one tool I’ve always been missing in my .NET development. Unfortunately, one perfect scenario for MEF tends to fall short of it’s full potential [...]]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://mef.codeplex.com/" target="_blank">Managed Extensibility Framework</a> is an amazingly useful addition to the .NET Framework.  I was very excited to see <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.composition(VS.100).aspx" target="_blank">System.ComponentModel.Composition</a> added to the core framework.  Personally, I feel that MEF is one tool I’ve always been missing in my .NET development.</p>
<p>Unfortunately, one perfect scenario for MEF tends to fall short of it’s full potential is in <a href="http://msdn.microsoft.com/en-us/library/ms754130.aspx" target="_blank">Windows Presentation Foundation</a> development.  In particular, there are many times when the XAML parser constructs objects in WPF development, which makes composition of those parts difficult.  The current release of MEF (Preview Release 9) addresses this for Silverlight developers via System.ComponentModel.Composition.CompositionInitializer.  However, there is no equivalent class for WPF developers.</p>
<p><span id="more-255"></span></p>
<p>The CompositionInitializer class provides the means for an object to compose itself.  This is very useful with WPF and Silverlight development, since it allows a View, such as a UserControl, to be generated via the standard XAML parser, and still automatically pull in the appropriate ViewModel in an extensible manner.  Glenn Block has demonstrated the <a href="http://blogs.msdn.com/gblock/archive/2010/03/08/building-hellomef-part-v-refactoring-to-viewmodel.aspx" target="_blank">usage for Silverlight in detail</a>, but the same issues apply in WPF.</p>
<p>As an example, let’s take a look at a very simple case.  Take the following XAML for a Window:</p>
<pre class="csharpcode"><span class="kwrd">&lt;</span><span class="html">Window</span> <span class="attr">x:Class</span><span class="kwrd">="WpfApplication1.MainView"</span>
        <span class="attr">xmlns</span><span class="kwrd">="http://schemas.microsoft.com/winfx/2006/xaml/presentation"</span>
        <span class="attr">xmlns:x</span><span class="kwrd">="http://schemas.microsoft.com/winfx/2006/xaml"</span>
        <span class="attr">Title</span><span class="kwrd">="MainWindow"</span> <span class="attr">Height</span><span class="kwrd">="220"</span> <span class="attr">Width</span><span class="kwrd">="300"</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">Grid</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">TextBlock</span> <span class="attr">Text</span><span class="kwrd">="{Binding TheText}"</span> <span class="kwrd">/&gt;</span>
    <span class="kwrd">&lt;/</span><span class="html">Grid</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">Window</span><span class="kwrd">&gt;</span></pre>
<p><!-- .csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } --> <!-- .csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->This does nothing but create a Window, add a simple TextBlock control, and use it to display the value of our “TheText” property in our DataContext class.  Since this is our main window, WPF will automatically construct and display this Window, so we need to handle constructing the DataContext and setting it ourselves.</p>
<p>We could do this in code or in XAML, but in order to do it directly, we would need to hard code the ViewModel type directly into our XAML code, or we would need to construct the ViewModel class and set it in the code behind.  Both have disadvantages, and the disadvantages grow if we’re using MEF to compose our ViewModel.</p>
<p>Ideally, we’d like to be able to have MEF construct our ViewModel for us.  This way, it can provide any construction requirements for our ViewModel via [ImportingConstructor], and it can handle fully composing the imported properties on our ViewModel.  CompositionInitializer allows this to occur.</p>
<p>We use CompositionInitializer within our View’s constructor, and use it for self-composition of our View.  Using CompositionInitializer, we can modify our code behind to:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">partial</span> <span class="kwrd">class</span> MainView : Window
{
    <span class="kwrd">public</span> MainView()
    {
        InitializeComponent();
        CompositionInitializer.SatisfyImports(<span class="kwrd">this</span>);
    }

    [Import(<span class="str">"MainViewModel"</span>)]
    <span class="kwrd">public</span> <span class="kwrd">object</span> ViewModel
    {
        get { <span class="kwrd">return</span> <span class="kwrd">this</span>.DataContext; }
        set { <span class="kwrd">this</span>.DataContext = <span class="kwrd">value</span>; }
    }
}</pre>
<p><!-- .csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->We then can add an Export on our ViewModel class like so:</p>
<pre class="csharpcode">[Export(<span class="str">"MainViewModel"</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> MainViewModel
{
    <span class="kwrd">public</span> <span class="kwrd">string</span> TheText
    {
        get
        {
            <span class="kwrd">return</span> <span class="str">"Hello World!"</span>;
        }
    }
}</pre>
<p>MEF will automatically compose our application, decoupling our ViewModel injection to the DataContext of our View until runtime.  When we run this, we’ll see:</p>
<p><a href="http://reedcopsey.com/blog/wp-content/uploads/2010/03/MainWindow1.png"><img style="display: block; float: none; margin-left: auto; margin-right: auto; border: 0px;" title="MainWindow" src="http://reedcopsey.com/blog/wp-content/uploads/2010/03/MainWindow_thumb1.png" border="0" alt="MainWindow" width="300" height="220" /></a></p>
<p>There are many other approaches for using MEF to wire up the extensible parts within your application, of course.  However, any time an object is going to be constructed by code outside of your control, CompositionInitializer allows us to continue to use MEF to satisfy the import requirements of that object.</p>
<p>In order to use this from WPF, I’ve ported the code from <a href="http://mef.codeplex.com/releases/view/40606" target="_blank">MEF Preview 9</a> and <a href="http://cid-f8b2fd72406fb218.skydrive.live.com/self.aspx/blog/Composition.Initialization.Desktop.zip?sa=947050772" target="_blank">Glenn Block’s (now obsolete) PartInitializer port</a> to Windows Presentation Foundation.  There are some subtle changes from the Silverlight port, mainly to handle running in a desktop application context.  The default behavior of my port is to construct an <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.composition.hosting.aggregatecatalog(VS.100).aspx" target="_blank">AggregateCatalog</a> containing a <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.composition.hosting.directorycatalog(VS.100).aspx" target="_blank">DirectoryCatalog</a> set to the location of the entry assembly of the application.  In addition, if an “Extensions” folder exists under the entry assembly’s directory, a second <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.composition.hosting.directorycatalog(VS.100).aspx" target="_blank">DirectoryCatalog</a> for that folder will be included.  This behavior can be overridden by specifying a <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.composition.hosting.compositioncontainer(VS.100).aspx" target="_blank">CompositionContainer</a> or one or more <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.composition.primitives.composablepartcatalog(VS.100).aspx" target="_blank">ComposablePartCatalogs</a> to the System.ComponentModel.Composition.Hosting.CompositionHost static class prior to the first use of CompositionInitializer.</p>
<p>Please download CompositionInitializer and CompositionHost for VS 2010 RC, and <a href="http://reedcopsey.com/contact-me/" target="_blank">contact me</a> with any feedback.</p>
<ul>
<li><strong><a href="http://reedcopsey.com/blog/wp-content/uploads/2010/03/Composition.Initialization.Desktop.zip" target="_blank">Composition.Initialization.Desktop.zip</a></strong></li>
</ul>
<h2>Edit on 3/29:</h2>
<p>Glenn Block has since updated his version of CompositionInitializer (and ExportFactory&lt;T&gt;!), and made it available here:</p>
<ul>
<li><a rel="nofollow" href="http://cid-f8b2fd72406fb218.skydrive.live.com/self.aspx/blog/Composition.Initialization.Desktop.zip">http://cid-f8b2fd72406fb218.skydrive.live.com/self.aspx/blog/Composition.Initialization.Desktop.zip</a></li>
</ul>
<p>This is a .NET 3.5 solution, and should soon be pushed to CodePlex, and made available on the main MEF site.</p>
]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2010/03/26/mef-compositioninitializer-for-wpf/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Better User and Developer Experiences &#8211; From Windows Forms to WPF with MVVM</title>
		<link>http://reedcopsey.com/2010/01/07/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm/</link>
		<comments>http://reedcopsey.com/2010/01/07/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm/#comments</comments>
		<pubDate>Thu, 07 Jan 2010 22:24:37 +0000</pubDate>
		<dc:creator>Reed</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[Windows Forms]]></category>

		<guid isPermaLink="false">http://reedcopsey.com/2010/01/07/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm/</guid>
		<description><![CDATA[This series introduces the Model-View-ViewModel Pattern from the point of view of a Windows Forms developer. The goal is not to introduce WPF, but to demonstrate some of the new features within Windows Presentation Foundation, and show how they should force every WPF developer to re-think how they design their applications. The Model-View-ViewModel pattern is [...]]]></description>
			<content:encoded><![CDATA[<p>This series introduces the Model-View-ViewModel Pattern from the point of view of a Windows Forms developer. The goal is not to introduce WPF, but to demonstrate some of the new features within Windows Presentation Foundation, and show how they should force every WPF developer to re-think how they design their applications.   <br />The Model-View-ViewModel pattern is introduced after a discussion of three of the main features in WPF which enable it&#8217;s usage. In order to illustrate this, three versions a single application were written:</p>
<ul>
<li>A Windows Forms application </li>
<li>A WPF Version of the application, using the same style </li>
<li>A WPF Version of the application, built using MVVM </li>
</ul>
<p>This allows a detailed understanding of the reasons behind MVVM, as well as the technology that enables the pattern.</p>
<p> <span id="more-150"></span>
<p>The series is written in multiple parts:</p>
<ul>
<li><a href="http://reedcopsey.com/2009/11/20/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-introduction/">Introduction</a></li>
<li><a href="http://reedcopsey.com/2009/11/23/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-1-the-model/">The Model</a></li>
<li><a href="http://reedcopsey.com/2009/11/24/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-2-our-application-in-windows-forms/">Our Application In Windows Forms</a></li>
<li><a href="http://reedcopsey.com/2009/11/24/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-3-our-application-in-wpf/">Our Application In WPF</a></li>
<li><a href="http://reedcopsey.com/2009/11/25/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-4-data-binding/">Data Binding</a></li>
<li><a href="http://reedcopsey.com/2009/12/28/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-5-commands/">Commands</a></li>
<li><a href="http://reedcopsey.com/2010/01/04/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-6-templating/">Templating</a></li>
<li><a href="http://reedcopsey.com/2010/01/06/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-7-mvvm/">MVVM</a></li>
<li><a href="http://reedcopsey.com/2010/01/07/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-conclusion/">Conclusion</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2010/01/07/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Better User and Developer Experiences &#8211; From Windows Forms to WPF with MVVM: Conclusion</title>
		<link>http://reedcopsey.com/2010/01/07/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-conclusion/</link>
		<comments>http://reedcopsey.com/2010/01/07/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-conclusion/#comments</comments>
		<pubDate>Thu, 07 Jan 2010 22:16:40 +0000</pubDate>
		<dc:creator>Reed</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[Windows Forms]]></category>

		<guid isPermaLink="false">http://reedcopsey.com/2010/01/07/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-conclusion/</guid>
		<description><![CDATA[Windows Presentation Foundation provides us with new opportunities to build applications that are very flexible to design, easy to maintain, and clear to understand.&#160; By taking advantage of Data Binding, Commands, and Templating, we can rethink the way we build our applications, and design them using the Model-View-ViewModel Pattern. Now that I’ve walked through how [...]]]></description>
			<content:encoded><![CDATA[<p>Windows Presentation Foundation provides us with new opportunities to build applications that are very flexible to design, easy to maintain, and clear to understand.&#160; By taking advantage of <a href="http://reedcopsey.com/2009/11/25/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-4-data-binding/">Data Binding</a>, <a href="http://reedcopsey.com/2009/12/28/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-5-commands/">Commands</a>, and <a href="http://reedcopsey.com/2010/01/04/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-6-templating/">Templating</a>, we can rethink the way we build our applications, and design them using the <a href="http://reedcopsey.com/2010/01/06/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-7-mvvm/">Model-View-ViewModel Pattern</a>.</p>
<p>Now that I’ve walked through how we do this, I will revisit our original RSS Feed Reader application, and show samples of how this changes the design and code in this simple application.</p>
<p> <span id="more-148"></span>
<p>First, lets look at our Model.</p>
<p>Our Model classes, as expected, remained completely unchanged through all three versions of our software.&#160; The same Model was usable by the Windows Forms application, our WPF application, and our WPF with MVVM version of our application.&#160; This works because our Model described nothing but it’s own, domain specific information.&#160; It took no dependencies on a presentation technology, and made no assumptions of how it would be used.</p>
<p>Next, lets begin by looking at our View.</p>
<p>In <a href="http://reedcopsey.com/2010/01/06/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-7-mvvm/">Part 7</a>, I mentioned that we should keep a goal in mind for the View: <strong>The user interface should be declared entirely in XAML, with zero code behind.&#160; </strong>Unfortunately, it’s impossible to have absolutely zero code, but we’ve managed to move our entire declaration of both our Window and our UserControl into XAML, so all that is left in the code is the constructor which calls InitializeComponent:</p>
<pre class="csharpcode"><span class="kwrd">namespace</span> RssMVVM.Views
{
    <span class="kwrd">public</span> <span class="kwrd">partial</span> <span class="kwrd">class</span> MainView
    {
        <span class="kwrd">public</span> MainView()
        {
            InitializeComponent();
        }
    }
}</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
</p>
<p>In this example, we’ve succeeded in accomplishing our goal – we have no code in the code behind other than the automatically generated code that is required to initialize our UserControl or WIndow.</p>
<p>Our XAML changed, as well.&#160; Instead of having nearly every element named in order to make them accessible via code, we now use data binding to bind directly to their values.&#160; For example, in our original WPF version of our UserControl, the first set of TextBox elements was written like this:</p>
<pre class="csharpcode"><span class="kwrd">&lt;</span><span class="html">TextBox</span> <span class="attr">Grid</span>.<span class="attr">Row</span><span class="kwrd">=&quot;0&quot;</span> <span class="attr">Grid</span>.<span class="attr">Column</span><span class="kwrd">=&quot;1&quot;</span> <span class="attr">x:Name</span><span class="kwrd">=&quot;textBoxTitle&quot;</span> <span class="kwrd">/&gt;</span>
<span class="kwrd">&lt;</span><span class="html">TextBox</span> <span class="attr">Grid</span>.<span class="attr">Row</span><span class="kwrd">=&quot;1&quot;</span> <span class="attr">Grid</span>.<span class="attr">Column</span><span class="kwrd">=&quot;1&quot;</span> <span class="attr">x:Name</span><span class="kwrd">=&quot;textBoxLink&quot;</span> <span class="kwrd">/&gt;</span>
<span class="kwrd">&lt;</span><span class="html">TextBox</span> <span class="attr">Grid</span>.<span class="attr">Row</span><span class="kwrd">=&quot;2&quot;</span> <span class="attr">Grid</span>.<span class="attr">Column</span><span class="kwrd">=&quot;1&quot;</span> <span class="attr">x:Name</span><span class="kwrd">=&quot;textBoxDescription&quot;</span> <span class="kwrd">/&gt;</span></pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>Now, in our MVVM version, we change this to:</p>
<pre class="csharpcode"><span class="kwrd">&lt;</span><span class="html">TextBox</span> <span class="attr">Grid</span>.<span class="attr">Row</span><span class="kwrd">=&quot;0&quot;</span> <span class="attr">Grid</span>.<span class="attr">Column</span><span class="kwrd">=&quot;1&quot;</span>
  <span class="attr">Text</span><span class="kwrd">=&quot;{Binding Path=Feed.Title, Mode=OneWay}&quot;</span> <span class="kwrd">/&gt;</span>
<span class="kwrd">&lt;</span><span class="html">TextBox</span> <span class="attr">Grid</span>.<span class="attr">Row</span><span class="kwrd">=&quot;1&quot;</span> <span class="attr">Grid</span>.<span class="attr">Column</span><span class="kwrd">=&quot;1&quot;</span>
  <span class="attr">Text</span><span class="kwrd">=&quot;{Binding Path=Feed.Link, Mode=OneWay, Converter={StaticResource StringToUriConverter}}&quot;</span> <span class="kwrd">/&gt;</span>
<span class="kwrd">&lt;</span><span class="html">TextBox</span> <span class="attr">Grid</span>.<span class="attr">Row</span><span class="kwrd">=&quot;2&quot;</span> <span class="attr">Grid</span>.<span class="attr">Column</span><span class="kwrd">=&quot;1&quot;</span>
  <span class="attr">Text</span><span class="kwrd">=&quot;{Binding Path=Feed.Description, Mode=OneWay}&quot;</span><span class="kwrd">/&gt;</span></pre>
<p>At first glance, this may seem like extra work.&#160; However, the second eliminates all of the code required to set and manage changes in the first (two entire methods).&#160; The MVVM version also has a subtle, yet profound advantage over the first: the XAML code is exactly describing what will exist inside that text box.&#160; This provides a level of self-documentation in your XAML, which fits in perfectly with it’s declarative nature.&#160; In the original version, the only clue we would have to the TextBox’s purpose is the name we specified.</p>
<p>I will mention – I had to “cheat” here, to some extent.&#160; There is one issue that was not easily resolved in porting this application to MVVM: the <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.webbrowser.aspx">WebBrowser control</a>.&#160; Unfortunately, the WebBrowser control wraps a COM component, and is not a native WPF control.&#160; I suspect that this led to an unfortunately design decision: <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.webbrowser.source.aspx">WebBrowser.Source</a> is not a standard WPF DependencyProperty, and as a result, can not be used with Data Binding like standard control elements.</p>
<p>There are at least two options for handling this situation.&#160; We could have easily handled this by using code in the code behind file.&#160; This would be a minor deviation from our goal, but as the goal of no code in code behind is a guideline, not a hard fixed rule, it would be a valid option.&#160; However, there is another feature in WPF we can use in many situations such as this: <a href="http://msdn.microsoft.com/en-us/library/ms749011.aspx">Attached Properties</a>.&#160; In my case, I prefer to use attached properties, since this creates a tool that is easily reusable on any WebBrowser control.&#160; By using an attached property, we can create a BindableSource property that allows us to use Data Binding with a WebBrowser, just by changing the XAML to:</p>
<pre class="csharpcode"><span class="kwrd">&lt;</span><span class="html">WebBrowser</span> <span class="attr">Grid</span>.<span class="attr">Row</span><span class="kwrd">=&quot;2&quot;</span> <span class="attr">RssMVVM:WebBrowserUtility</span>.<span class="attr">BindableSource</span><span class="kwrd">=&quot;{Binding Uri}&quot;</span> <span class="kwrd">/&gt;</span></pre>
<p>The final change I introduced was the addition of a DataTemplate in the application’s XAML: </p>
<pre class="csharpcode"><span class="kwrd">&lt;</span><span class="html">Application.Resources</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">DataTemplate</span> <span class="attr">DataType</span><span class="kwrd">=&quot;{x:Type ViewModels:FeedViewModel}&quot;</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">Views:FeedControl</span> <span class="kwrd">/&gt;</span>
    <span class="kwrd">&lt;/</span><span class="html">DataTemplate</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">Application.Resources</span><span class="kwrd">&gt;</span></pre>
<p>This simple addition allows <a href="http://reedcopsey.com/2010/01/04/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-6-templating/">WPF’s templating</a> to automatically construct and manage our View for the UserControl, saving us all of the code required to construct and place the control.</p>
<p>We made our clean View possible by introducing two ViewModel classes: <strong>MainViewModel</strong> and <strong>FeedViewModel</strong>.&#160; Looking at our ViewModel classes, we see their simplicity.&#160; Most of the code involved in our ViewModel class is nothing but a wrapper around our Model in order to allow it to properly implement <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx">INotifyPropertyChanged</a>, and to handle the creation of our <a href="http://msdn.microsoft.com/en-us/library/system.windows.input.icommand.aspx">ICommand</a> implementations.</p>
<p>The nice thing here, is we can see all of our logic, everything that the View is going to use, in one location.&#160; There is nothing tied to a specific View here, so it is easy to generate unit tests for our ViewModel classes.&#160; All of our logic is wrapped into a commands, and the rest of our ViewModel classes do nothing but wrap properties to properly handle INotifyPropertyChanged.</p>
<p>I purposely did not make custom styles for the WPF versions of this application.&#160; That would be very easy to do, and potentially could make the WPF versions of this application much better looking and more usable.&#160; Though it would be a fun and easy exercise, the main goal of this series is to demonstrate how the code itself can be changed in order to make maintaining and redesigning the application simple – not how to make a beautiful designed user interface.</p>
<p>The Visual Studio Solution used in this article, with full source code, is available on <a href="http://code.msdn.microsoft.com/WinFormToWPFMVVM">MSDN Code Gallery</a>.&#160; I encourage you to download and compare all three versions of the RSS Feed Reader application in detail.&#160; The progression of this application, and the advantages it brings, will be much more noticeable when looking at the full source code.</p>
<p>Windows Presentation Foundation has a lot to offer every application developer.&#160; By taking advantage of its unique features, we can build our applications in a way that is maintainable, testable, designable, and simple to implement.&#160; The Model-View-ViewModel design pattern provides a clean pattern we can use improve our efficiency as developers.</p>
]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2010/01/07/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-conclusion/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Better User and Developer Experiences &#8211; From Windows Forms to WPF with MVVM: Part 7, MVVM</title>
		<link>http://reedcopsey.com/2010/01/06/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-7-mvvm/</link>
		<comments>http://reedcopsey.com/2010/01/06/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-7-mvvm/#comments</comments>
		<pubDate>Thu, 07 Jan 2010 01:40:11 +0000</pubDate>
		<dc:creator>Reed</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[Windows Forms]]></category>

		<guid isPermaLink="false">http://reedcopsey.com/2010/01/06/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-7-mvvm/</guid>
		<description><![CDATA[I mentioned in the introduction that a new architectural pattern has emerged for Windows Presentation Foundation: Model-View-ViewModel.&#160; As I mentioned, MVVM can make developing applications in WPF efficient, quick, and highly maintainable.&#160; Now that I’ve covered some of the basic technological advances in WPF, mainly Data Binding, Commands, and Templating, it’s time to bring everything [...]]]></description>
			<content:encoded><![CDATA[<p>I mentioned in the <a href="http://reedcopsey.com/2009/11/20/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-introduction/">introduction</a> that a new <a href="http://en.wikipedia.org/wiki/Architectural_pattern_(computer_science)">architectural pattern</a> has emerged for Windows Presentation Foundation: <a href="http://en.wikipedia.org/wiki/MVVM">Model-View-ViewModel</a>.&#160; As I mentioned, MVVM can make developing applications in WPF efficient, quick, and highly maintainable.&#160; Now that I’ve covered some of the basic technological advances in WPF, mainly <a href="http://reedcopsey.com/2009/11/25/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-4-data-binding/">Data Binding</a>, <a href="http://reedcopsey.com/2009/12/28/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-5-commands/">Commands</a>, and <a href="http://reedcopsey.com/2010/01/04/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-6-templating/">Templating</a>, it’s time to bring everything together, and demonstrate how this improves our jobs as developers.</p>
<p> <span id="more-145"></span>
<p>As I mentioned in the section on templating, WPF’s design strives to maintain a clear separation between presentation and logic.&#160; We’ve seen some of the advantages in terms of control creation – unlike Windows Forms, we can completely change the way a control looks merely by creating a new template, using XAML in a completely declarative form.&#160; No code is required.&#160; We get more flexibility with less work.&#160; By separating presentation and logic, WPF creates opportunities for much greater degrees of flexibility in our applications.</p>
<p>As a developer, I see this as a very “good thing”.&#160; The Model-View-ViewModel pattern has one goal – to extend this same flexibility into our applications by creating <em>and maintaining</em> a clean <a href="http://en.wikipedia.org/wiki/Separation_of_concerns">separation of concerns</a> through our entire application.</p>
<p>In order to understand MVVM, I will start off by defining our distinct <a href="http://en.wikipedia.org/wiki/Concern_(computer_science)">concerns</a>, the individual “parts” of our application.&#160; </p>
<p>I already defined our arguably most important concern: <a href="http://reedcopsey.com/2009/11/23/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-1-the-model/">the Model</a>.&#160; Again, the Model is the domain-specific data and logic used within your application.&#160; It’s the goal – the “data” you’re working to expose to your users.&#160; This may be customer records in a database, or product information on a website, or anything else.&#160; In our case, it’s two classes, the <strong>Feed</strong> and the <strong>FeedItem</strong> class.&#160; In Model-View-ViewModel, our goal is to keep the model unaware of the specific application or technology that’s using it.&#160; The Model knows about itself, and nothing else.</p>
<p>The second concern I’ll discuss is the View.&#160; The View is the entire user interface of your application – it’s everything the user’s interact with directly: every control, every button, every check box, every window.&#160; As I <a href="http://reedcopsey.com/2009/11/24/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-3-our-application-in-wpf/">mentioned in part 3</a>, WPF changes how the View is normally defined.&#160; Instead of developing the user interface via code, we use XAML to create an XML-based, declarative description of the interface.</p>
<p>Let’s review our goal of maintaining a full separation of presentation and logic, this time just in terms of the View.&#160; When we create our user interface, we want to define what the user will see (presentation) without worrying about how the program works (logic).&#160; XAML is perfect for this, as it lets us design the user interface with zero code involved.&#160; This gives us an easy way to think about our View<strong> </strong>in terms of our goal: <strong>The user interface should be declared entirely in XAML, with zero code behind.</strong></p>
<p>Succeeding in this goal has many advantages.&#160; It makes the View very flexible – a designer can take our View and stylize it or change it in any way desired, without changing or effecting a single line of code.&#160; Also, if there is no logic in the View itself, it eliminates the risk of “stale” or unused code creeping into the View, which often happens in Windows Forms.</p>
<p>Now that we have the View and the Model defined, we need a way to hook the two things together.&#160; Something has to coordinate our actions between the Model and the View, so that the user’s interaction has an effect on the Model.&#160; This is handled by our third concern: the ViewModel.</p>
<p>The ViewModel serves the purpose of adapting the Model to be <strong>directly usable by the View</strong>.&#160; In order to do this, we take advantage of <a href="http://reedcopsey.com/2009/11/25/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-4-data-binding/">WPF’s incredible Data Binding support</a>.&#160; In MVVM, the ViewModel sits between the View and the Model, and basically acts similar to an <a href="http://en.wikipedia.org/wiki/Adapter_pattern">Adapter</a> – it translates the properties and methods of the Model to a form that can be directly used via Data Binding.</p>
<p>The ViewModel also provides us a place to manage application state and logic.&#160; By taking advantage of <a href="http://reedcopsey.com/2009/12/28/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-5-commands/">WPF’s Commanding Infrastructure</a>, we can define ICommand instances in the ViewModel that the View can directly access via Data Binding.&#160; This provides us a clean way to keep the logic out of the View – again, the View works completely via Data Binding to the ViewModel.&#160; This provides a means by which we can hook into logic from the View without having the logic be tied to the specific view that is using it.</p>
<p>Here is a diagram illustrating our three areas of concern:</p>
<p><a href="http://reedcopsey.com/blog/wp-content/uploads/2010/01/MVVM.png"><img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="MVVM" border="0" alt="MVVM" src="http://reedcopsey.com/blog/wp-content/uploads/2010/01/MVVM_thumb.png" width="404" height="739" /></a>There are some important aspects of this diagram I will discuss, for each of our Concerns, some critical points</p>
<ul>
<li>The Model
<ul>
<li>The Model is unaware of anything except itself </li>
<li>The Model could be used by any form of program, and is not tied to a specific framework or technology </li>
</ul>
</li>
<li>The View
<ul>
<li>The View is defined entirely in XAML </li>
<li>The View only needs to know what to bind to, by name.&#160; It does not need to know anything about what will happen when properties change or commands are executed. </li>
<li>The View’s state is completely based upon data binding </li>
</ul>
</li>
<li>The ViewModel
<ul>
<li>The ViewModel knows nothing about the View </li>
<li>The ViewModel directly interacts with the Model, in order to expose it for data binding </li>
<li>The ViewModel manages the Application-specific information </li>
</ul>
</li>
</ul>
<p>The advantages here are profound:</p>
<p>Our Model, since it is self contained, can be used in any way we wish.&#160; If, later, we decided we needed a web-based API to the same model, we could use the Model unchanged.&#160; If the successor to WPF comes along, and we need to update our application to use it, the Model remains unchanged.</p>
</p>
<p>Our View, since it has no logic, is completely designable.&#160; The View can be modified by a designer with little or no programming experience, with no fear of breaking the logic.&#160; The only knowledge that the designer needs to know is what properties and commands are available, and their names – everything else is handled directly by the framework to make it work.&#160; This leads to a tremendous amount of flexibility in the View – the entire look and feel of an application can be changed at any time.</p>
<p>Our ViewModel gets a nice advantage from this architecture, as well.&#160; Since it is not tied to a specific View, it is very easily testable.&#160; The logic of our application is all exposed through self-contained ICommand implementations, which are easy to test.&#160; The data is exposed via properties; again, easy to test.</p>
<p>There is still one issue left to resolve, though.&#160; At this point, we know how to architect a single window or form correctly – the Model is used by the ViewModel, and the View “hooks” into the ViewModel with data binding.&#160; This works great for a single user control – but we still need to create and wire up the controls in the first place.</p>
<p>At first glance, it seems like we’d need to know about the View and the ViewModel in order to do this.&#160; For the ViewModel to be used as a binding source, it needs to be set as the DataContext of the correct View.&#160; We need a way, given a ViewModel, to construct a View and set its DataContext.&#160; In order to do this, we break one of our rules – the ViewModel, in order to construct the View, needs to know about the Views.</p>
<p>WPF, again, provides us with the final tool required for MVVM: <a href="http://reedcopsey.com/2010/01/04/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-6-templating/">Templating</a>.&#160; The same mechanism that our ListBox used when we discussed templating can be used for our ViewModel.&#160; Instead of trying to construct our View, we can setup a simple DataTemplate that specifies that our View is used to render our ViewModel.&#160; This will look similar to:</p>
<pre class="csharpcode"><span class="kwrd">&lt;</span><span class="html">DataTemplate</span> <span class="attr">DataType</span><span class="kwrd">=&quot;{x:Type local:OurViewModel}&quot;</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">local:OurView</span> <span class="kwrd">/&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">DataTemplate</span><span class="kwrd">&gt;</span></pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>This DataTemplate tells WPF that, any time we say to directly render an instance of <strong>OurViewModel</strong>, it should construct an instance of <strong>OurView</strong>, place it at that location, and set the DataContext of the OurView instance to the instance of OurViewModel.&#160; Basically, WPF will do all of the work for us, just be specifying a DataTemplate.</p>
<p>Since DataTemplates are definable in XAML, and will propagate downwards through the Visual Tree in WPF, this lets our View automatically set itself up.&#160; All that needs to happen is to provide a ContentPresenter in our View which binds, using standard DataBinding, to a ViewModel, and WPF will do all of the plumbing for us!</p>
<p>WPF adds three profound features: <a href="http://reedcopsey.com/2009/11/25/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-4-data-binding/">Data Binding</a>, <a href="http://reedcopsey.com/2009/12/28/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-5-commands/">Commands</a>, and <a href="http://reedcopsey.com/2010/01/04/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-6-templating/">Templates</a>.&#160; By using these three feature sets appropriately, we can redesign the architecture of our applications by using the Model-View-ViewModel pattern. This maintains a clear separation of concerns, allows for easy changes and redesign of the View, provides good testability, and keeps our domain specific classes completely isolated.</p>
<p><a href="http://reedcopsey.com/2010/01/07/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-conclusion/">… Continued in the Conclusion …</a></p>
]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2010/01/06/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-7-mvvm/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Better User and Developer Experiences &#8211; From Windows Forms to WPF with MVVM: Part 6, Templating</title>
		<link>http://reedcopsey.com/2010/01/04/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-6-templating/</link>
		<comments>http://reedcopsey.com/2010/01/04/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-6-templating/#comments</comments>
		<pubDate>Tue, 05 Jan 2010 01:02:33 +0000</pubDate>
		<dc:creator>Reed</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[Windows Forms]]></category>

		<guid isPermaLink="false">http://reedcopsey.com/2010/01/04/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-6-templating/</guid>
		<description><![CDATA[In order to rethink how we architect and write client applications, there is one last important concept Windows Presentation Foundation introduces, beyond the excellent Data Binding and Commanding support I’ve already discussed.&#160; WPF adds an entire suite of features specifically related to Styling and Templating.&#160; This is often discussed in relation to improving the overall [...]]]></description>
			<content:encoded><![CDATA[<p>In order to rethink how we architect and write client applications, there is one last important concept <a href="http://msdn.microsoft.com/en-us/library/ms754130.aspx">Windows Presentation Foundation</a> introduces, beyond the excellent <a href="http://reedcopsey.com/2009/11/25/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-4-data-binding/">Data Binding</a> and <a href="http://reedcopsey.com/2009/12/28/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-5-commands/">Commanding</a> support I’ve already discussed.&#160; WPF adds an entire suite of features specifically related to <a href="http://msdn.microsoft.com/en-us/library/ms745683.aspx">Styling and Templating</a>.&#160; This is often discussed in relation to improving the overall look, feel, and usability of applications written using WPF – the key to the new user experience (UX) WPF allows.&#160; However, the templating engine introduced with WPF has other side effects, which change the way we should design our software, not just change the way we stylize our software.</p>
<p> <span id="more-136"></span>
<p>Windows Presentation Foundation, in its design, strives to keep a clear separation of presentation and logic.&#160; This is apparent throughout <a href="http://msdn.microsoft.com/en-us/library/ms750441.aspx">its architecture</a>, but perhaps most notable in one of the core building blocks of every WPF application: the <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.control.aspx">Control class</a>.&#160; </p>
<p>Controls, in WPF, have two completely separate parts.&#160; There is the logical portion, and then there is a <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.controltemplate.aspx">ControlTemplate</a> that defines how the control is represented visually; how the control looks.&#160; The difference in thinking, even in this core element, is apparent from the documentation.</p>
<p>Here is how the <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.control.aspx">Control class in Windows Forms</a> is described in MSDN:</p>
<blockquote><p>Defines the base class for controls, which are components with visual representation.</p></blockquote>
<p>Compare that to the <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.control.aspx">Control class in WPF</a>:</p>
<blockquote><p>Represents the base class for user interface (UI) elements that use a ControlTemplate to define their appearance.</p></blockquote>
<p>Note the difference here.&#160; Even the most basic definition of a “Control”, the core component used to build applications, has changed in Windows Presentation Foundation.&#160; In Windows Forms, when you defined a control, you defined everything about the control directly.&#160; Take a button – a button not only had to deal with the fact that it has behavior (its something visual on which you click, which in turn triggers behavior) – it also directly handled its own rendering.&#160; Typically, if you wanted to make a <em>Button </em>that looked dramatically different from the standard button, you’d make a custom control (ie: a separate class), where you’d handle, not only the button’s behavior, but also all of the code required to paint the customized button.&#160; In WPF, making custom controls is much less common – instead of making a separate class for the new button, you could just make a custom <a href="http://msdn.microsoft.com/en-us/library/ms745683.aspx#styling_controltemplates">Style, a ControlTemplate</a> which completely changes the way the button is rendered.&#160; However, the behavior of the button is the same, since it’s still uses the standard “Button” class.</p>
<p>This is the key to making WPF applications highly designable – it’s very easy to allow a designer to go in and completely customize the look and feel of every part of your application <strong>without introducing custom controls</strong>.&#160; Many people tout this as WPF’s advantage over Windows Forms, as well as nearly every other preceding UI technology.</p>
<p>In our case, however, we’re interested in how to architect our application from a code standpoint, not how to make it pretty.&#160; The styling and templating engine in WPF provides another very critical component: the <a href="http://msdn.microsoft.com/en-us/library/system.windows.datatemplate.aspx">DataTemplate</a>.</p>
<p>Data templates are most often used by WPF controls whose purpose is to display a collection of items.&#160; These typically are the classes that derive from <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.aspx">ItemsControl</a>, such as <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.listbox.aspx">ListBox</a> and <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.treeview.aspx">TreeView</a>.&#160; For our purposes, lets look at ListBox.</p>
<p>In Windows Forms, when you had a ListBox, by default it just displayed a list of items as text.&#160; Changing this required <a href="http://msdn.microsoft.com/en-us/library/ms229679.aspx">creating an owner drawn list box</a>, which was a challenge, even for a simple change in style.&#160; This requires handling your own GDI+ drawing using the Graphics class, and pushed everything into code that is difficult to write and maintain.</p>
<p>In WPF, this is handled by a <a href="http://msdn.microsoft.com/en-us/library/system.windows.datatemplate.aspx">DataTemplate</a>.&#160; By default, you can bind a collection of any objects to a ListBox, and the ListBox will list the results of calling <a href="http://msdn.microsoft.com/en-us/library/system.object.tostring.aspx">Object.ToString()</a> on each element of the collection.&#160; Custom drawing is handled very easily by using a DataTemplate.&#160; In the <a href="http://msdn.microsoft.com/en-us/library/ms745683.aspx#styling_datatemplates">Styling and Templating example</a>, the DataTemplate creates a Border with a nested Image, bound to the Source property of each element.&#160; This causes the ListBox to display a list of Images.</p>
<p>In our RSS Feed Reader, we use the same technique to display a list of FeedItems.&#160; Our ListBox is bound directly to a list of our RssModel.FeedItem class, and without a DataTemplate, we see:</p>
<p><a href="http://reedcopsey.com/blog/wp-content/uploads/2010/01/ListNoTemplate.png"><img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="ListBox with No Template" border="0" alt="ListBox with No Template" src="http://reedcopsey.com/blog/wp-content/uploads/2010/01/ListNoTemplate_thumb.png" width="372" height="484" /></a> </p>
<p>However, in our UserControl, we added a very simple DataTemplate:</p>
<pre class="csharpcode"><span class="kwrd">&lt;</span><span class="html">DataTemplate</span> <span class="attr">DataType</span><span class="kwrd">=&quot;{x:Type model:FeedItem}&quot;</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">TextBlock</span> <span class="attr">Text</span><span class="kwrd">=&quot;{Binding Path=Title}&quot;</span> <span class="kwrd">/&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">DataTemplate</span><span class="kwrd">&gt;</span></pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>This causes our display to change.&#160; Now, instead of just listing the class name (the default behavior of ToString() on our RssModel.FeedItem class), we display a TextBlock containing the FeedItem’s Title property:</p>
<p><a href="http://reedcopsey.com/blog/wp-content/uploads/2010/01/ListWithTemplate.png"><img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="ListWithTemplate" border="0" alt="ListWithTemplate" src="http://reedcopsey.com/blog/wp-content/uploads/2010/01/ListWithTemplate_thumb.png" width="359" height="484" /></a> </p>
<p>This is much nicer, and very simple to implement.&#160; </p>
<p>DataTemplates, however, go far beyond just displaying Text – we could have displayed borders, images, text, or any other complex item we wished, merely by specifying a template in our UserControl.&#160; The idea behind a DataTemplate is that you specify, in XAML, how <strong>any object should be represented visually</strong>.&#160; This lets us tell the user interface to <strong>directly render a custom class</strong>, without the code needing to know or worry about the class being rendered properly.</p>
<p>In our case, we used that to customize the display of a list of FeedItems.&#160; The <a href="http://msdn.microsoft.com/en-us/library/ms745683.aspx#styling_datatemplates">MSDN sample</a> displayed a list of Photo classes using pictures surrounded by a border.&#160; This flexibility is the key to rethinking our architecture, and in our final installment, I’ll delve into how and why this should change the way you think about designing client applications.</p>
<p><a href="http://reedcopsey.com/2010/01/06/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-7-mvvm/">… Continued in Part 7, MVVM …</a></p>
]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2010/01/04/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-6-templating/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Better User and Developer Experiences &#8211; From Windows Forms to WPF with MVVM: Part 5, Commands</title>
		<link>http://reedcopsey.com/2009/12/28/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-5-commands/</link>
		<comments>http://reedcopsey.com/2009/12/28/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-5-commands/#comments</comments>
		<pubDate>Tue, 29 Dec 2009 01:40:12 +0000</pubDate>
		<dc:creator>Reed</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://reedcopsey.com/2009/12/28/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-5-commands/</guid>
		<description><![CDATA[In the last article, I explained how Windows Presentation Foundation improves upon data handling via it’s excellent support for data binding.&#160; However, data is only part of the equation.&#160; In order to be a more effective framework, WPF also provides us a way to more effectively handle our application specific logic. It does this by [...]]]></description>
			<content:encoded><![CDATA[<p>In the <a href="http://reedcopsey.com/?p=104">last article</a>, I explained how Windows Presentation Foundation improves upon data handling via it’s excellent support for data binding.&#160; However, data is only part of the equation.&#160; In order to be a more effective framework, WPF also provides us a way to more effectively handle our application specific logic.</p>
<p>It does this by providing a unified model for separating the originator of an action from the effect produced by the action, via the <a href="http://msdn.microsoft.com/en-us/library/ms752308.aspx">Commanding</a> infrastructure.</p>
</p>
<p> <span id="more-122"></span>Commands in WPF are a very powerful abstraction.&#160; MSDN clearly states the goals of the commanding infrastructure:
</p>
<pre>What makes commands different from a simple event handler
attached to a button or a timer is that commands separate the
semantics and the originator of an action from its logic.
This allows for multiple and disparate sources to invoke the
same command logic, and it allows the command logic to be
customized for different targets.</pre>
<p>This follows a simple, but pervasive goal in WPF – separation of logic from presentation.&#160; In the case of commands, the goal is to decouple an “action” from the object on which its working, as well as from the user interface element that triggers the action.</p>
<p>Also MSDN’s <a href="http://msdn.microsoft.com/en-us/library/ms752308.aspx">Commanding discussion</a> focuses on the <a href="http://msdn.microsoft.com/en-us/library/system.windows.input.routedcommand.aspx">RoutedCommand</a> implementations, for our purposes, we’ll use the <a href="http://msdn.microsoft.com/en-us/library/system.windows.input.icommand.aspx">ICommand interface</a> directly.&#160; ICommand is a simple interface, and it provides two functions:</p>
<ol>
<li>Provide a means (CanExecute method) to determine whether an action can be run in the current context, as well as a way to track when this changes (CanExecuteChanged event). </li>
<li>Provide a method (Execute) to perform a given action </li>
</ol>
<p>By providing this in a simple interface, we can make our own class which wraps this functionality into any series of delegates.&#160; In our case, we made an ICommand class called ActionCommand, which lets us do some nice things.</p>
<p>For example, in the DataContext we use for our specific feed information UserControl, we start off by defining an ICommand as a property:</p>
<pre class="csharpcode"><span class="rem">/// &lt;summary&gt;</span>
<span class="rem">/// Gets the open feed command.</span>
<span class="rem">/// &lt;/summary&gt;</span>
<span class="rem">/// &lt;value&gt;The open feed command.&lt;/value&gt;</span>
<span class="kwrd">public</span> ICommand OpenFeedCommand
{
    get;
    <span class="kwrd">private</span> set;
}</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p><!-- .csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->We then initialize this directly using:</p>
<pre class="csharpcode"><span class="kwrd">this</span>.OpenFeedCommand = <span class="kwrd">new</span> ActionCommand(<span class="kwrd">this</span>.OpenFeed, () =&gt; <span class="kwrd">true</span>);</pre>
<p>Basically, this provides us a Property, directly on our DataContext, that lets us call an OpenFeed method.&#160; Also, since we can now directly expose the SelectedFeedItem due to Data Binding (as discussed in <a href="http://reedcopsey.com/2009/11/25/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-4-data-binding/">part 4</a>), we simplify our logic as well.</p>
<p>Now, in our code, we can replace our event handler:</p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">void</span> ButtonOpenLink_Click(<span class="kwrd">object</span> sender, RoutedEventArgs e)
{
    <span class="kwrd">if</span> (<span class="kwrd">this</span>.Feed != <span class="kwrd">null</span>)
    {
        FeedItem item = <span class="kwrd">this</span>.Feed.Items[<span class="kwrd">this</span>.listBoxFeeds.SelectedIndex];
        <span class="kwrd">if</span> (item != <span class="kwrd">null</span>)
        {
            System.Diagnostics.Process.Start(item.Link.AbsoluteUri);
        }
    }
}</pre>
<p>With a dramatically simplified OpenFeed method:</p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">void</span> OpenFeed()
{
    <span class="kwrd">if</span> (<span class="kwrd">this</span>.SelectedFeedItem != <span class="kwrd">null</span>)
    {
        System.Diagnostics.Process.Start(<span class="kwrd">this</span>.SelectedFeedItem.Link.AbsoluteUri);
    }
}</pre>
<p>Our XAML will change, so instead of using the event handler, we switch to specifying the Command for our button directly, using <a href="http://reedcopsey.com/2009/11/25/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-4-data-binding/">WPF’s DataBinding</a>:</p>
<pre class="csharpcode"><span class="kwrd">&lt;</span><span class="html">Button</span>
   <span class="attr">Grid</span>.<span class="attr">Row</span><span class="kwrd">=&quot;1&quot;</span> <span class="attr">Grid</span>.<span class="attr">Column</span><span class="kwrd">=&quot;1&quot;</span> <span class="attr">Height</span><span class="kwrd">=&quot;23&quot;</span>
   <span class="attr">HorizontalAlignment</span><span class="kwrd">=&quot;Right&quot;</span> <span class="attr">Margin</span><span class="kwrd">=&quot;0,0,0,0&quot;</span>
   <span class="attr">VerticalAlignment</span><span class="kwrd">=&quot;Top&quot;</span> <span class="attr">Width</span><span class="kwrd">=&quot;60&quot;</span>
   <span class="attr">Command</span><span class="kwrd">=&quot;{Binding OpenFeedCommand}&quot;</span><span class="kwrd">&gt;</span>
Open
<span class="kwrd">&lt;/</span><span class="html">Button</span><span class="kwrd">&gt;</span></pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p><!-- .csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->Note the differences here in approach – we’re accomplishing the same goal (hooking our code into the button being clicked by the user), but in a very different way. </p>
<p>In Windows Forms, and even in WPF when we use the event approach, we’re directly handling the button’s click event, and our logic gets mixed with the fact that we’re using a button in the interface.&#160; If we were to change from a button to a menu, or a hyperlink, or some other control, we’d have to change our code to handle the different type of event, and move our logic across.&#160; The code is always aware of what control is triggering some action.</p>
<p>Now, by using an ICommand, we’re doing something different.&#160; What we are accomplishing here is making two statements in our code:</p>
<ol>
<li>Our user should be able to call a command to Open a feed (OpenFeedCommand) </li>
<li>The OpenFeedCommand performs this function (launches the browser with the feed’s URI). </li>
</ol>
<p>Nothing in the code knows how this command will get invoked – it can be from a button’s click (as it is here), but it could just as easily be triggered by any <a href="http://msdn.microsoft.com/en-us/library/system.windows.input.icommandsource.aspx">ICommandSource</a>, including a <a href="http://msdn.microsoft.com/en-us/library/system.windows.documents.hyperlink.aspx">Hyperlink</a>, <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.menuitem.aspx">MenuItem</a>, or even a <a href="http://msdn.microsoft.com/en-us/library/system.windows.input.keygesture.aspx">KeyGesture</a>.</p>
<p>The important point here is that the code does not know, or care, what triggered it.&#160; We could rework the user interface to use completely different controls <strong>without changing one line of C# code</strong>, because we decoupled the action from what triggered the action by using a Command.</p>
<p><a href="http://reedcopsey.com/2010/01/04/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-6-templating/">… Continued in Part 6, Templating …</a></p>
]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2009/12/28/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-5-commands/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Better User and Developer Experiences &#8211; From Windows Forms to WPF with MVVM: Part 4, Data Binding</title>
		<link>http://reedcopsey.com/2009/11/25/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-4-data-binding/</link>
		<comments>http://reedcopsey.com/2009/11/25/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-4-data-binding/#comments</comments>
		<pubDate>Thu, 26 Nov 2009 01:56:00 +0000</pubDate>
		<dc:creator>Reed</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[Windows Forms]]></category>

		<guid isPermaLink="false">http://reedcopsey.com/?p=104</guid>
		<description><![CDATA[Now that I’ve demonstrated how WPF can be written in the same manner, using the same methods as prior windowing frameworks, it’s time to explain why this is a bad idea.&#160; To do this effectively, I’m going to discuss a few things that WPF introduces, and explain how they should change the way all of [...]]]></description>
			<content:encoded><![CDATA[<p>Now that I’ve demonstrated how WPF can be written in the same manner, using the same methods as prior windowing frameworks, it’s time to explain why this is a bad idea.&#160; To do this effectively, I’m going to discuss a few things that WPF introduces, and explain how they should change the way all of us approach building user interfaces.&#160; One thing I do want to mention – this series is not meant to be a full tutorial on WPF, rather an explanation of how to use features in WPF effectively.</p>
<p>The first new concept in WPF I’ll introduce is the new, more powerful, more flexible model for <a href="http://msdn.microsoft.com/en-us/library/ms752347.aspx">Data Binding</a>.</p>
</p>
<p> <span id="more-104"></span>Windows Presentation Foundation provides an entirely new form of <a href="http://msdn.microsoft.com/en-us/library/ms752347.aspx">Data Binding</a> than previous data binding technologies.&#160; <a href="http://msdn.microsoft.com/en-us/library/ef2xyb33.aspx">Data Binding existed in Windows Forms</a>, but was limited to being bound to pretty specific <a href="http://msdn.microsoft.com/en-us/library/f3y6cb0c.aspx">data sources</a>.&#160; Many developers have used data bound controls prior to WPF, but the way data binding works in WPF has changed.&#160; The data binding support in WPF adds the potential to use completely different programming models than we used previously.
</p>
<p>So lets start with explaining data binding, in general terms.&#160; <a href="http://en.wikipedia.org/wiki/Data_binding">Data binding</a> is a general purpose technique that lets you take two (or potentially more than two) separate elements, and “bind” them together so that their values stay synchronized.&#160; Typically, a control in the user interface (like a text box or a label) is bound to a property on some object containing your business logic.</p>
<p>The advantages of this should be obvious pretty quickly, provided this works correctly.&#160; However, previous attempts at data binding have all fallen short when it came time to use them in practical, real-world problems.&#160; I believe this comes down to the inability of most data binding frameworks to handle everything required.&#160; For data binding to truly be effective, a binding framework should provide the following.</p>
<ul>
<li>An easy way to bind user interface elements to data sources </li>
<li>A clean way to specify a data source for an entire collection of objects </li>
<li>A consistent way to specify bindings, no matter what is being bound </li>
<li>Allow flexibility in what triggers updates </li>
<li>An effective means of validation of values </li>
<li>The means to do conversion of the data through the binding itself </li>
</ul>
<p>Most frameworks for data binding have provided some, but not all, of the features available above.&#160; I’m going to address the above bullet points, and show how WPF provides for clean data binding.&#160; We’ll start with the first three points:</p>
<ul>
<li>An easy way to bind user interface elements to data sources </li>
<li>A clean way to specify a data source for an entire collection of objects </li>
<li>A consistent way to specify bindings, no matter what is being bound </li>
</ul>
<p>Nearly all user interface items in WPF derive from <a href="http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.aspx">FrameworkElement</a>.&#160; Whenever you create a Window or a UserControl in WPF, you have the option of specifying <strong>any object</strong> as the Framework Element’s <a href="http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.datacontext.aspx">DataContext</a>.&#160; The DataContext property specifies “the data context for an element when it participates in data binding”.&#160; Whenever an object has a DataContext specified, you can use WPF’s data binding to bind directly to properties defined on that object.</p>
<p>There is a very important line in the documentation for <a href="http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.datacontext.aspx">DataContext</a>:</p>
<pre>This dependency property inherits property values. If there are child
elements without other values for DataContext established through local values
or styles, then the property system will set the value to be the DataContext
value of the nearest parent element with this value assigned.</pre>
<p>What this means is that you don’t have to specify the DataContext for every element in your Window or UserControl.&#160; You can specify the DataContext for a UserControl, and, by default, <strong>every control inside of the UserControl will automatically use that same DataContext for data binding</strong>!&#160; This is incredibly powerful.</p>
<p>For example, in both our <a href="http://reedcopsey.com/?p=100">Windows Forms</a> and <a href="http://reedcopsey.com/?p=103">WPF (version 1)</a> applications, we had a UserControl defined for displaying information about our Feed object.&#160; Whenever we’d update our Feed object, we would write a bunch of code triggered by setting our property to update our UI, such as:</p>
<pre class="csharpcode"><span class="rem">// .. Called when Feed changes to update the user interface</span>
    <span class="kwrd">this</span>.textBoxTitle.Text = <span class="kwrd">this</span>.Feed.Title;
    <span class="kwrd">this</span>.textBoxLink.Text = <span class="kwrd">this</span>.Feed.Link.AbsoluteUri;
    <span class="kwrd">this</span>.textBoxDescription.Text = <span class="kwrd">this</span>.Feed.Description;</pre>
<p>
  </p>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p><!--.csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } --></p>
<p>By using data binding, we can completely eliminate this code.&#160; Instead of doing this, we could, for example, just set the DataContext of our UserControl to the Feed object itself.&#160; Once we’ve done that, we can just specify, in our XAML (which can be done in the designer), which property in our DataContext which we want to bind to our individual TextBox controls:</p>
<pre class="csharpcode"><span class="kwrd">&lt;</span><span class="html">TextBox</span> <span class="attr">Grid</span>.<span class="attr">Row</span><span class="kwrd">=&quot;0&quot;</span> <span class="attr">Grid</span>.<span class="attr">Column</span><span class="kwrd">=&quot;1&quot;</span> <span class="attr">Text</span><span class="kwrd">=&quot;{Binding Path=Feed.Title, Mode=OneWay}&quot;</span> <span class="kwrd">/&gt;</span>
<span class="kwrd">&lt;</span><span class="html">TextBox</span> <span class="attr">Grid</span>.<span class="attr">Row</span><span class="kwrd">=&quot;1&quot;</span> <span class="attr">Grid</span>.<span class="attr">Column</span><span class="kwrd">=&quot;1&quot;</span> <span class="attr">Text</span><span class="kwrd">=&quot;{Binding Path=Feed.Link.AbsoluteUri, Mode=OneWay}&quot;</span> <span class="kwrd">/&gt;</span>
<span class="kwrd">&lt;</span><span class="html">TextBox</span> <span class="attr">Grid</span>.<span class="attr">Row</span><span class="kwrd">=&quot;2&quot;</span> <span class="attr">Grid</span>.<span class="attr">Column</span><span class="kwrd">=&quot;1&quot;</span> <span class="attr">Text</span><span class="kwrd">=&quot;{Binding Path=Feed.Description, Mode=OneWay}&quot;</span><span class="kwrd">/&gt;</span></pre>
<p><!-- .csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } --></p>
<p>Now, all of a sudden, we have full, up to date user interface controls, and we can completely eliminate two entire methods (<em>ResetFeed</em> and <em>ClearFeed</em>) from our code!&#160; Less code means less to maintain, less to test, and less to worry about.&#160; Our TextBox instances don’t have a DataContext specified, so they automatically inherit the DataContext of the UserControl (since that is the first parent element with a DataContext provided).&#160; They then bind directly to the property of the object in the DataContext.</p>
<p>This solves our first three bullet points – we can bind to <strong>any object </strong>(*see note below) using <strong>declarative syntax</strong> (in XAML), and we can <strong>specify the object one time</strong>, at a high level such as a Window or UserControl, via <a href="http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.datacontext.aspx">FrameworkElement.DataContext</a>.</p>
<p>Let’s move on to the next two points:</p>
<ul>
<li>Allow flexibility in what triggers updates </li>
<li>An effective means of validation of values </li>
</ul>
<p>Windows Presentation Foundation provides the means to handle this, as well.&#160; Again, with no changes to our code, we can declaratively add support for both of the above bullet points.</p>
<p>First, what triggers an <a href="http://msdn.microsoft.com/en-us/library/ms752347.aspx#what_triggers_source_updates">update to the binding can be specified</a>, in XAML, by providing an <a href="http://msdn.microsoft.com/en-us/library/system.windows.data.binding.updatesourcetrigger.aspx">UpdateSourceTrigger</a>.&#160; This lets us say, explicitly, that we want the property to update every time we type a letter into a TextBox (by setting the trigger to “PropertyChanged”), or only when the control loses focus (“LostFocus”).&#160; In addition, <a href="http://msdn.microsoft.com/en-us/library/system.windows.data.updatesourcetrigger.aspx">UpdateSourceTrigger</a> lets us explicitly handle property updates, even though this is not as commonly used.</p>
<p>Validation can be handled, and again specified declaratively by using XAML, in multiple ways.&#160; I do not want to cover Validation here in detail, but it is <a href="http://msdn.microsoft.com/en-us/library/ms752347.aspx#data_validation">discussed in detail on MSDN</a>.&#160; One or more ValidationRules can be attached to a Binding, allowing for great flexibility in data validation.</p>
<p>Let’s look at our final point:</p>
<ul>
<li>The means to do conversion of the data through the binding itself </li>
</ul>
<p>Using WPF, we have the ability to bind objects of any type to a control, even if the type wouldn’t normally (directly) be editable or displayable within a control.&#160; WPF allows you to specify a converter to use to convert from the source type to the editing type, as well as handling the conversion back.&#160; This is done via <a href="http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter.aspx">IValueConverter</a>.&#160; By specifying your own value converter, you can bind, via both OneWay or TwoWay binding, any control to any type of object.&#160; For example, above, we bound our TextBox to “Feed.Link.AbsoluteUri”, which is a string.&#160; However, if the AbsoluteUri property didn’t exist, we could write a converter to convert from a <a href="http://msdn.microsoft.com/en-us/library/system.uri.aspx">Uri</a> to a string, and use that in our data binding.&#160; This would allow us to bind directly to “Feed.Link”, as follows:</p>
<pre class="csharpcode"><span class="kwrd">&lt;</span><span class="html">TextBox</span> <span class="attr">Grid</span>.<span class="attr">Row</span><span class="kwrd">=&quot;1&quot;</span> <span class="attr">Grid</span>.<span class="attr">Column</span><span class="kwrd">=&quot;1&quot;</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">TextBox.Text</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">Binding</span> <span class="attr">Path</span><span class="kwrd">=&quot;Feed.Link&quot;</span> <span class="attr">Mode</span><span class="kwrd">=&quot;OneWay&quot;</span><span class="kwrd">&gt;</span>
            <span class="kwrd">&lt;</span><span class="html">Binding.Converter</span><span class="kwrd">&gt;</span>
                <span class="kwrd">&lt;</span><span class="html">RssMVVM:StringToUriConverter</span> <span class="kwrd">/&gt;</span>
            <span class="kwrd">&lt;/</span><span class="html">Binding.Converter</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;/</span><span class="html">Binding</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;/</span><span class="html">TextBox.Text</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">TextBox</span><span class="kwrd">&gt;</span></pre>
<p>This is critical to the flexibility of WPF’s data binding – we’re now directly binding a string (the TextBox.Text property) to a custom class (<a href="http://msdn.microsoft.com/en-us/library/system.uri.aspx">Uri</a>).&#160; We can now data bind to any type of object, which allows us to do very complex operations.&#160; For example, we can now display different images for Enum values (by having a converter that converts from the Enum value to an image).</p>
<p>To summarize, the data binding in Windows Presentation Foundation provides us with a simple, clean, powerful, and flexible means of displaying our properties inside our user interfaces, as well as automatically updating our properties when the user edits values within controls in our user interfaces.&#160; In addition, it does it in a way that’s completely declarative, with no code required.</p>
<p><em>* Although you can bind to any object, there are certain types of objects that work better.&#160; In particular, any object that implements INotifyPropertyChanged or derives from DependencyObject will allow for TwoWay binding to work properly.&#160; Collections should implement INotifyCollectionChanged or IBindingList in order to allow for proper TwoWay binding, as well.&#160; This isn’t a requirement, but it is worth mentioning, since it has a large impact on usability.</em></p>
<p><a href="http://reedcopsey.com/2009/12/28/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-5-commands/">… Continued in Part 5, Commands …</a></p>
]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2009/11/25/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-4-data-binding/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Better User and Developer Experiences &#8211; From Windows Forms to WPF with MVVM: Part 3, Our Application in WPF</title>
		<link>http://reedcopsey.com/2009/11/24/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-3-our-application-in-wpf/</link>
		<comments>http://reedcopsey.com/2009/11/24/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-3-our-application-in-wpf/#comments</comments>
		<pubDate>Wed, 25 Nov 2009 02:10:46 +0000</pubDate>
		<dc:creator>Reed</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[Windows Forms]]></category>

		<guid isPermaLink="false">http://reedcopsey.com/?p=103</guid>
		<description><![CDATA[One common misconception I see when people start off with WPF is that they feel that it’s unapproachable, too complicated, and too unwieldy.&#160; There some fundamental shifts that every developer must deal with when the first switch to WPF, but they are actually fairly minor.&#160; You can program against the Windows Presentation Foundation API using [...]]]></description>
			<content:encoded><![CDATA[<p>One common misconception I see when people start off with WPF is that they feel that it’s unapproachable, too complicated, and too unwieldy.&#160; There some fundamental shifts that every developer must deal with when the first switch to WPF, but they are actually fairly minor.&#160; You can program against the <a href="http://msdn.microsoft.com/en-us/library/ms754130.aspx">Windows Presentation Foundation</a> API using the same basic techniques that you used in Windows Forms.</p>
<p> <span id="more-103"></span>
<p>The first thing you’ll notice when working with WPF is the change in how the designer works.&#160; The same concepts are there – you can drag controls onto a <a href="http://msdn.microsoft.com/en-us/library/system.windows.window.aspx">Window</a> or a <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.usercontrol(VS.95).aspx">UserControl</a>, and move them around, perform layout, etc.&#160; There are some differences in how things work, especially in regards to layout, but for the most part, a developer can still open a window, drag in controls, and place them using the same basic technique as the Windows Forms designer.</p>
<p>However, when this is done, the designer does something very different.&#160; In Windows Forms, the designer wrote our code for us; it created a partial class, and in the <em>.designer.cs</em> file, we got all of the code required to programmatically create our user interface.&#160; This fit well with Windows Form’s <a href="http://en.wikipedia.org/wiki/Imperative_programming">imperative programming</a> style.&#160; The WPF designer, on the other hand, builds its user interface by creating <em>.xaml</em> files instead, using the <a href="http://msdn.microsoft.com/en-us/library/ms752059.aspx">Extensible Application Markup Language</a>.&#160; Microsoft describes XAML as “A Declarative Language with Flow Control Support”; the key word here is “declarative.”&#160; WPF uses a <a href="http://en.wikipedia.org/wiki/Declarative_programming">declarative programming</a> model, at least for the creation of the user interface.&#160; Instead of specifying the steps required to build the user interface, the compiler uses a markup file (based on XML) that describes what should be displayed, not how to display it.</p>
<p>This is the single, fundamental change in thinking required to use WPF.&#160; Even then, this is handled completely by the designer, so technically, you can build an entire user interface and never even look at this, just as you could build a Windows Forms user interface and never look at the designer file.</p>
<p>WPF also provides similar, often identical, events on controls for each control type.&#160; For example, <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.button.aspx">Button</a> provides a <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.buttonbase.click.aspx">Click event</a>, to which you can subscribe.&#160; The <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.textbox.aspx">TextBox</a> control provides a <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.textbox.text.aspx">Text</a> property you can set. This lets you wire up your event handlers in a manner that is nearly identical to Windows Forms.</p>
<p>For this part of our Series, we’re going to demonstrate this.&#160; We’re going to write the same application we wrote using <a href="http://reedcopsey.com/?p=100">Windows Forms in Part 2</a>, this time, using WPF.</p>
<p>First thing to notice &#8211; the application looks very similar:</p>
<p><a href="http://reedcopsey.com/blog/wp-content/uploads/2009/11/WPFFeedReaderMain.png"><img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="WPFFeedReaderMain" border="0" alt="WPFFeedReaderMain" src="http://reedcopsey.com/blog/wp-content/uploads/2009/11/WPFFeedReaderMain_thumb.png" width="350" height="484" /></a>The main differences are due to changes in the default styling of WPF’s controls vs. those of Windows Forms.&#160; Functionally, the application is identical.&#160; It uses the same <a href="http://reedcopsey.com/?p=90">Model classes</a>, completely unchanged.&#160; I performs the same functions, with the same basic behavior.&#160; We even structured it the same way, using a <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.usercontrol(VS.95).aspx">UserControl</a> for the center section of the Window.</p>
<p>When we look at the code, we find something even more surprising – the code is nearly identical to our Windows Forms application!</p>
<p>For example, our “Load RSS Feed” button in our main Window class has a click event handler attached to it, and just like our Windows Forms application, it does nothing but load the Feed using the Model, and set a property in the UserControl.&#160; The only difference here is in the declaration of our method: instead of passing <strong>EventArgs e</strong>, we now pass <strong>RoutedEventArgs e</strong>.&#160; Otherwise, the code is identical:</p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">void</span> ButtonUpdateFeed_Click(<span class="kwrd">object</span> sender, RoutedEventArgs e)
{
    <span class="kwrd">this</span>.feedControl.Feed = Feed.Read(<span class="kwrd">new</span> Uri(<span class="kwrd">this</span>.textBoxFeedUrl.Text));
}</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>Just like before, this sets the “Feed” property within our UserControl, but this time, <strong>the code in our UserControl is exactly the same as our Windows Forms code!&#160; </strong>We were able to copy the code, with absolutely no changes, from Windows Forms to WPF.&#160; Here is a small subset of that code, just to demonstrate that it hasn’t changed:</p>
<pre class="csharpcode"><span class="rem">// ... previous code from Windows Forms application</span>
    <span class="kwrd">this</span>.textBoxTitle.Text = <span class="kwrd">this</span>.Feed.Title;
    <span class="kwrd">this</span>.textBoxLink.Text = <span class="kwrd">this</span>.Feed.Link.AbsoluteUri;
    <span class="kwrd">this</span>.textBoxDescription.Text = <span class="kwrd">this</span>.Feed.Description;

    <span class="kwrd">foreach</span> (var item <span class="kwrd">in</span> <span class="kwrd">this</span>.Feed.Items)
    {
        <span class="kwrd">this</span>.listBoxFeeds.Items.Add(item.Title);
    }
<span class="rem">// ... continue with code from Windows Forms application</span></pre>
<p>In fact, when we look at our UserControl’s code behind file (the file that ends in .xaml.cs), the only differences we have between our WPF code and our Windows Forms code, through the entire Window and UserControl, are subtle differences in the method declaration, and setting “.Source” instead of “.Url” in our Main window, since WPF has different delegate declarations for its events and some subtle differences in control APIs.&#160; Otherwise, the code we wrote is identical, to the letter.</p>
<p>Windows Presentation Foundation, though new, does not force us as developers to change our programming style.&#160; We can do things the way we’ve always done them in Windows Forms, and continue forward with newer technology.&#160; We can even mix and match Windows Forms and WPF via <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.integration.elementhost.aspx">ElementHost</a> and <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.integration.windowsformshost.aspx">WindowsFormsHost</a>, which let us host WPF inside Windows Forms and Windows Forms inside WPF.</p>
<p>Here are the important points to realize from this part of the series:</p>
<ul>
<li>Although WPF is a completely new API, you can use the same <a href="http://en.wikipedia.org/wiki/Event-driven_programming">event-driven programming</a> style that you used in Windows Forms. </li>
<li>Most of the “new” features in WPF are optional.&#160; WPF can make a real application using the same techniques as Windows Forms, only now, some of the interface is defined <a href="http://en.wikipedia.org/wiki/Declarative_programming">declaratively</a> instead of being entirely <a href="http://en.wikipedia.org/wiki/Imperative_programming">imperative</a>. </li>
</ul>
<p>Hopefully, this mitigates some of the concern and fear of moving from Windows Forms to WPF.&#160; There really is no reason to avoid using Windows Presentation Foundation, even if I haven’t described (yet) the compelling reasons to migrate, and the numerous advantages of WPF.</p>
<p><a href="http://reedcopsey.com/2009/11/25/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-4-data-binding/">… Continued in Part 4, Data Binding …</a></p>
]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2009/11/24/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-3-our-application-in-wpf/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Better User and Developer Experiences &#8211; From Windows Forms to WPF with MVVM: Part 2, Our Application in Windows Forms</title>
		<link>http://reedcopsey.com/2009/11/24/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-2-our-application-in-windows-forms/</link>
		<comments>http://reedcopsey.com/2009/11/24/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-2-our-application-in-windows-forms/#comments</comments>
		<pubDate>Wed, 25 Nov 2009 00:53:10 +0000</pubDate>
		<dc:creator>Reed</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[Windows Forms]]></category>

		<guid isPermaLink="false">http://reedcopsey.com/?p=100</guid>
		<description><![CDATA[In order to fully understand how and why to migrate from Windows Forms to WPF, and from WPF to WPF using MVVM, we need to understand Windows Forms. When Microsoft first developed and released .NET, they provided a very clean, simple API for creating Windows applications based upon existing technologies: Windows Forms.&#160; The Windows Forms [...]]]></description>
			<content:encoded><![CDATA[<p>In order to fully understand how and why to migrate from Windows Forms to WPF, and from WPF to WPF using MVVM, we need to understand <a href="http://msdn.microsoft.com/en-us/library/dd30h2yb.aspx">Windows Forms</a>.</p>
<p>When Microsoft first developed and released .NET, they provided a very clean, simple API for creating Windows applications based upon existing technologies: Windows Forms.&#160; The Windows Forms programming model is an <a href="http://en.wikipedia.org/wiki/Event-driven_application">event based programming model</a>.&#160; This matches very well with prior Microsoft technologies, such as ATL and MFC, since the core of Windows Forms wraps around controls defined in the Windows API.</p>
<p> <span id="more-100"></span>
<p>In Windows Forms, you start with a “Form”, which corresponds to a Window in the desktop.&#160; The form contains multiple controls, each done via a wrapper around the Controls in the Windows API.&#160; Each control provides its own window handle (<a href="http://msdn.microsoft.com/en-us/library/aa383751(VS.85).aspx">HWND</a>, via <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.control.handle.aspx">Control.Handle</a>), which is basically a separate <a href="http://msdn.microsoft.com/en-us/library/ms632595(VS.85).aspx">Window</a>.&#160; When the application starts, you create a windows message pump by calling <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.application.run.aspx">Application.Run</a>, which maps the standard windows messages to their appropriate controls, which in turn raise <a href="http://msdn.microsoft.com/en-us/library/8627sbea.aspx">events</a> in the code for the Form.</p>
<p>In addition, a full designer was built which takes care of the initialization of the form, so the developer can graphically layout their controls on a form, and the appropriate C# code will be generated (inside the InitializeComponent method) on the fly.&#160; It will add event handlers for the developer, and map them to methods in the Form’s .cs file automatically, making the creation of quick GUIs very easy.</p>
<p>Microsoft also provided a means of compartmentalizing a form, breaking it into more managable, smaller pieces of functionality called a <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.usercontrol.aspx">UserControl</a>.&#160; A <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.usercontrol.aspx">UserControl</a> is basically the “guts” of a form that you can drop into another form, allowing both reuse in multiple forms, but also separation of logic into pieces to prevent a form from getting too large, in terms of code.</p>
<p>This is a very similar, comfortable model for developers who have used MFC, VB6, or even Delphi.&#160; The implementation details are slightly different, but the basic conceptual model was unchanged – design a form, hook up events, handle the events, always working with the message pump in code.&#160; This made adoption of the Windows Forms model very fast – it was familiar, and easy to transition from other technologies to Windows Forms.</p>
<p>For our series, we’re going to start here.&#160; Taking <a href="http://reedcopsey.com/?p=90">our Model</a>, the Feed and FeedItem classes described previously, we’re going to wire up a simple RSS Feed Reader application using Windows Forms.&#160; </p>
<p>This is a very simple application.&#160; For our purposes, the application must:</p>
<ul>
<li>Load the feed using the Model </li>
<li>Display the basic information about the Feed </li>
<li>Display the list of FeedItems in the Feed </li>
<li>Let the user choose a specific FeedItem </li>
<li>Allow the user to open a FeedItem’s original source in their browser </li>
<li>Display the FeedItem in a wrapped browser </li>
</ul>
<p>Here is a screenshot of our completed Windows Forms application:</p>
<p><a href="http://reedcopsey.com/blog/wp-content/uploads/2009/11/WinFormFeedReaderMain.png"><img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="WinFormFeedReaderMain" border="0" alt="WinFormFeedReaderMain" src="http://reedcopsey.com/blog/wp-content/uploads/2009/11/WinFormFeedReaderMain_thumb.png" width="363" height="484" /></a> There’s nothing fancy in this application, and the code should look very familiar to anyone who’s used Windows Forms.&#160; So, let’s look at how this works internally…</p>
<p>The “Feed Information” and “Select a Feed Item” section are broken into a separate UserControl for demonstration purposes.&#160; The user interface was completely generated inside of a designer, and the code was written for us.&#160; </p>
<p>When the user clicks on “Load RSS Feed”, a small event handler is run:</p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">void</span> ButtonUpdateFeed_Click(<span class="kwrd">object</span> sender, EventArgs e)
{
    <span class="kwrd">this</span>.feedControl.Feed = Feed.Read(<span class="kwrd">new</span> Uri(<span class="kwrd">this</span>.textBox1.Text));
}</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>This sets the “Feed” property within our UserControl to a Feed (our Model).&#160; The UserControl has a “Feed” property, which specifies some code to run when the Feed is updated:</p>
<pre class="csharpcode"><span class="kwrd">public</span> Feed Feed
{
    get
    {
        <span class="kwrd">return</span> <span class="kwrd">this</span>.feed;
    }

    set
    {
        <span class="kwrd">this</span>.feed = <span class="kwrd">value</span>;
        <span class="kwrd">this</span>.ResetFeed();
    }
}</pre>
<p>This, in turn, calls the ResetFeed() method, which first calls ClearFeed() to cleanup the current UI, and then sets values inside each control:</p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">void</span> ResetFeed()
{
    <span class="kwrd">this</span>.ClearFeed();

    <span class="kwrd">if</span> (<span class="kwrd">this</span>.Feed == <span class="kwrd">null</span>)
    {
        <span class="kwrd">return</span>;
    }

    <span class="kwrd">this</span>.textBoxTitle.Text = <span class="kwrd">this</span>.Feed.Title;
    <span class="kwrd">this</span>.textBoxLink.Text = <span class="kwrd">this</span>.Feed.Link.AbsoluteUri;
    <span class="kwrd">this</span>.textBoxDescription.Text = <span class="kwrd">this</span>.Feed.Description;

    <span class="kwrd">foreach</span> (var item <span class="kwrd">in</span> <span class="kwrd">this</span>.Feed.Items)
    {
        <span class="kwrd">this</span>.listBoxFeeds.Items.Add(item.Title);
    }
}

<span class="kwrd">private</span> <span class="kwrd">void</span> ClearFeed()
{
    <span class="kwrd">this</span>.listBoxFeeds.Items.Clear();
    <span class="kwrd">this</span>.textBoxTitle.Text = <span class="kwrd">string</span>.Empty;
    <span class="kwrd">this</span>.textBoxLink.Text = <span class="kwrd">string</span>.Empty;
    <span class="kwrd">this</span>.textBoxDescription.Text = <span class="kwrd">string</span>.Empty;
    <span class="kwrd">this</span>.textBoxItemTitle.Text = <span class="kwrd">string</span>.Empty;
    <span class="kwrd">this</span>.textBoxItemLink.Text = <span class="kwrd">string</span>.Empty;
    <span class="kwrd">this</span>.textBoxItemDescription.Text = <span class="kwrd">string</span>.Empty;
}</pre>
<p>Our user control gets filled in with all of the feed information by us.&#160; When the user chooses a feed in the ListBox control, we handle it via another event handler:</p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">void</span> ListBoxFeeds_SelectedIndexChanged(<span class="kwrd">object</span> sender, EventArgs e)
{
    FeedItem item = <span class="kwrd">this</span>.Feed.Items[<span class="kwrd">this</span>.listBoxFeeds.SelectedIndex];
    <span class="kwrd">this</span>.textBoxItemTitle.Text = item.Title;
    <span class="kwrd">this</span>.textBoxItemLink.Text = item.Link.AbsoluteUri;
    <span class="kwrd">this</span>.textBoxItemDescription.Text = item.Description;

    <span class="kwrd">if</span> (<span class="kwrd">this</span>.UriChanged != <span class="kwrd">null</span>)
    {
        <span class="kwrd">this</span>.UriChanged(<span class="kwrd">this</span>, <span class="kwrd">new</span> UriChangedEventArgs(<span class="kwrd">new</span> Uri(<span class="kwrd">this</span>.textBoxItemLink.Text)));
    }
}</pre>
<p>When our selected feed item changes, we update the feed item’s controls, and also raise an event on our UserControl.&#160; Our main form subscribes to this event, and uses it to update the WebBrowser control sitting underneath our UserControl in the Form.</p>
<p>Finally, we have a button labeled “Open”, which has an event handler attached to it to open the Feed in our browser:</p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">void</span> ButtonOpenLink_Click(<span class="kwrd">object</span> sender, EventArgs e)
{
    <span class="kwrd">if</span> (<span class="kwrd">this</span>.Feed != <span class="kwrd">null</span>)
    {
        FeedItem item = <span class="kwrd">this</span>.Feed.Items[<span class="kwrd">this</span>.listBoxFeeds.SelectedIndex];
        <span class="kwrd">if</span> (item != <span class="kwrd">null</span>)
        {
            System.Diagnostics.Process.Start(item.Link.AbsoluteUri);
        }
    }
}</pre>
<p>This should look familiar to most Windows Forms programmers.&#160; There are other ways to write this type of code, but this is very common, and seems quite indicative of how many Windows Forms programs are written.&#160; This is by no means meant to be a perfect example of a great Windows Forms application, but rather a typical, common way this application could have been written.</p>
<p>There are some important things to realize here.&#160; </p>
<ul>
<li>All of our logic is handled in events, triggered by the user interacting with the user interface in our Window. </li>
<li>Although the Windows Forms designer provides a nice interface, if you actually examine the code, the entire user interface is defined <a href="http://en.wikipedia.org/wiki/Imperative_programming">imperitively</a>, whether by us or by the designer. </li>
<li>The code, and therefore the logic, is really dependent on the type of control being used.&#160; For example, if we changed from a ListBox to some other type of control, we’d most likely need to change the code to compensate </li>
</ul>
<p><a href="http://reedcopsey.com/2009/11/24/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-3-our-application-in-wpf/">… Continued in Part 3, Our Application in WPF …</a></p>
]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2009/11/24/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-2-our-application-in-windows-forms/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Better User and Developer Experiences &#8211; From Windows Forms to WPF with MVVM: Part 1, The Model</title>
		<link>http://reedcopsey.com/2009/11/23/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-1-the-model/</link>
		<comments>http://reedcopsey.com/2009/11/23/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-1-the-model/#comments</comments>
		<pubDate>Tue, 24 Nov 2009 01:12:25 +0000</pubDate>
		<dc:creator>Reed</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://reedcopsey.com/?p=90</guid>
		<description><![CDATA[Before we can make a user interface for a program, we need to know what the program is going to do.&#160; Hopefully, we have some logic we’re going to be exposing to our users.&#160; Underneath all of the beautiful user interfaces we build there is something that we’re trying to accomplish, some data we’re editing [...]]]></description>
			<content:encoded><![CDATA[<p>Before we can make a user interface for a program, we need to know what the program is going to do.&#160; Hopefully, we have some logic we’re going to be exposing to our users.&#160; Underneath all of the beautiful user interfaces we build there is something that we’re trying to accomplish, some data we’re editing or information we’re conveying.&#160; Before we can discuss how to make an effective user experience, we need to define the core information with which we are working.</p>
<p> <span id="more-90"></span>When we discuss software architecturally, the core elements of our program are the “Model”.&#160; The terminology comes from <a href="http://en.wikipedia.org/wiki/Architectural_pattern_(computer_science)">architectural design patterns</a>, and goes back pretty far.&#160; The “Model” is the one thing in most user interface patterns that hasn’t changed, and is the same terminology used all the way back with Smalltalk in the 70’s when Trygve Reenskaug first described the <a href="http://en.wikipedia.org/wiki/Model-view-controller">Model-View-Controller</a> pattern.
</p>
<p>When we’re talking about the Model, we’re talking about the domain-specific data and logic – the “guts” inside the program itself.&#160; In an ideal world, the program should be able to, at least theoretically and architecturally, work without the user interface being present at all, <strong>provided it has the appropriate information</strong> passed to it.&#160; The core business logic, in an ideal world, doesn’t need or want to know anything about how it’s being used – that’s outside of its <a href="http://en.wikipedia.org/wiki/Concern_(computer_science)">concern</a>.</p>
<p>Your business logic should know about your business, and nothing else.&#160; This is key to maintaining an effective <a href="http://en.wikipedia.org/wiki/Separation_of_concerns">separation of concerns</a> within the design of our program.&#160; This is also very useful for maintaining a program over time.&#160; Keeping the model separate makes it much easier to extend an application into other realms without duplication of code or breaking a deployed application.&#160; For example, if your business logic is completely isolated, you could potentially switch, without changing your business logic, from using a desktop, client-side application to using a command line, script based version of your application.&#160; In some situations, you can even take the same logic and host it, accessing it remotely via a web page.</p>
<p>In most cases, its easiest to think of the Model as the data.&#160; If you are making an application to edit customer information, the customer information (data) is the Model.&#160; The model can also encapsulate logic, however.&#160; If you have a service that needs to be called as part of your business logic when data is updated, the service itself can be thought of as part of the model.&#160; When you talk about your program, when you discuss what <strong>functions the program performs</strong>, such as it “works on” this (data) or “performs this task” (logic), you are talking about the model.&#160; Any time you discuss <strong>how the user interacts with the program</strong>, however, you are talking outside of the concern of the Model.</p>
<p>I want to mention, as a side note, one other thing here, that I often see as a point of confusion.&#160; If you have an application with a full, multi-tier data access layer, all of the data access and logic layers are part of (or under) the Model.&#160; For our purposes, we treat data and logic tiers as an internal, private implementation detail of the Model.&#160; Here, the business logic layer acts as the Model&#8217;s public API, and we use that as our Model.&#160; Presentation is separate from the Model, but the things the user &quot;works on&quot; (the data and domain specific logic to manipulate the data) are part of the Model.</p>
<p>For our series, we’re going to work with a simple program that is just an RSS feed reader.&#160; When we’re talking about the feed reader applications, all three versions of our application we will develop use the same Model.&#160; The public API of the Model is nothing but 2 classes: a <strong>Feed</strong> and a <strong>FeedItem</strong>.&#160; The Feed class has some properties (Title, Description, etc), as well as a collection of FeedItem instances.&#160; The FeedItem class contains properties for information about each item in the feed, including a Title, a Link to the original item, and a Description of the feed item.&#160; The Feed class also has some logic – it has a static method that allows it to create a Feed given a Uri.</p>
<p>There is one important thing to remember about our Feed and FeedItem classes – they just describe data, and provide a means to load it.&#160; They do not describe, in any way, how to edit or display the data.&#160; Because the Model is all about data, and not about presentation or manipulation of that data by the user, we can use the same assembly, unchanged, in all three versions of our application.</p>
<p><a href="http://reedcopsey.com/2009/11/24/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-2-our-application-in-windows-forms/">… Continued in Part 2, Our Application in Windows Forms …</a></p>
]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2009/11/23/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-1-the-model/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Better User and Developer Experiences &#8211; From Windows Forms to WPF with MVVM: Introduction</title>
		<link>http://reedcopsey.com/2009/11/20/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-introduction/</link>
		<comments>http://reedcopsey.com/2009/11/20/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-introduction/#comments</comments>
		<pubDate>Sat, 21 Nov 2009 01:26:39 +0000</pubDate>
		<dc:creator>Reed</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://reedcopsey.com/?p=89</guid>
		<description><![CDATA[I frequently talk to people trying to decide, for a new project, between Windows Forms and Windows Presentation Foundation.&#160; After spending time with WPF, I feel there is no reason to choose Windows Forms for new development.&#160; WPF, when used correctly, is far superior, both in terms of user experience, but also developer productivity. I [...]]]></description>
			<content:encoded><![CDATA[<p>I frequently talk to people trying to decide, for a new project, between Windows Forms and Windows Presentation Foundation.&#160; After spending time with WPF, I feel there is no reason to choose Windows Forms for new development.&#160; WPF, when used correctly, is far superior, both in terms of user experience, but also developer productivity.</p>
<p>I feel that the confusion around choosing WPF really stems from a lack of understanding about WPF.&#160; Even people on my own team have been overwhelmed trying to understand how the different pieces of WPF fit together, and how to apply the new concepts introduced with WPF effectively.&#160; In order to address this, I’m going to break this down into a few simple pieces, and show the migration in terms of thought required to transition from being a good Windows Forms developer to an effective WPF developer.</p>
</p>
<p> <span id="more-89"></span>
</p>
<p>Windows Presentation Foundation is huge.&#160; Do not doubt it.&#160; It is huge, both in terms of scope, but also in terms of the radically different approach it takes to developing user interfaces than other technologies.&#160; Don’t let the scope frighten you, however – it is very well thought out, and very usable, once you understand some of the basic concepts.</p>
<p>In addition to the huge scope of WPF, new design patterns have evolved to take advantage of the new features introduced by this framework.&#160; The most commonly referenced one, in terms of WPF, seems to be MVVM, or Model-View-ViewModel.&#160; The Model-View-ViewModel pattern was inspired by some of the features in WPF, and seems perfectly fit for WPF, so many developers advocate it (with good reason) for use with WPF.</p>
<p>Again, don’t let this frighten or discourage you… MVVM isn’t about making WPF more difficult, it’s about making WPF usable in a quick, efficient manner.&#160; Learning MVVM actually makes understanding WPF easier, not more difficult.</p>
<p>The issue here is that WPF is large, and the framework doesn’t force you into a single way of working.&#160; There are lots of ways to work with WPF, including doing nearly the exact thing you’re used to with Windows Forms!&#160; This is part of the power and flexibility of WPF, but also a trap to watch for and to avoid.&#160; MVVM helps guide and force you to take advantage of WPF’s new features effectively, insulating you from common pitfalls and mistakes.</p>
<p>For this series, I’m going to start by showing a simple Windows Forms application – an RSS Feed Reader, and demonstrate converting it to WPF.&#160; I’ll start with a strait conversion – and demonstrate how you can make WPF look and work exactly the same as you can with Windows Forms.&#160; I’ll then explain, in details, some of the new ways of thinking that are pervasive within WPF, and show how this should change your way of thinking about user interfaces.</p>
<p>In order to do this, we’ll work with four separate projects – which include three completely different versions of the same application.&#160; The goal here isn’t to use WPF to make the application “pretty” or “flashy”, rather, it’s to show how you can use WPF to make an application more developer friendly, including making it cleaner, more logical, easier to maintain, and more testable.</p>
<p><a href="http://reedcopsey.com/2009/11/23/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-1-the-model/">… Continued in Part 1, The Model …</a></p>
]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2009/11/20/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-introduction/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>WPF &#8211; Common Dependency Property Exception</title>
		<link>http://reedcopsey.com/2009/10/23/wpf-common-dependency-property-exception/</link>
		<comments>http://reedcopsey.com/2009/10/23/wpf-common-dependency-property-exception/#comments</comments>
		<pubDate>Fri, 23 Oct 2009 20:49:45 +0000</pubDate>
		<dc:creator>Reed</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://reedcopsey.com/?p=67</guid>
		<description><![CDATA[Unlike standard .NET properties, implementing a DependencyProperty requires a bit more code, and has the potential to cause nasty errors to creep up at runtime, without any compile time warnings.&#160; Here’s one easy, common mistake, as well as an explanation of why it occurs… Take a look at the following DependencyProperty implementation: public static DependencyProperty [...]]]></description>
			<content:encoded><![CDATA[<p>Unlike standard .NET properties, implementing a <a href="http://msdn.microsoft.com/en-us/library/system.windows.dependencyproperty.aspx">DependencyProperty</a> requires a bit more code, and has the potential to cause nasty errors to creep up at runtime, without any compile time warnings.&#160; Here’s one easy, common mistake, as well as an explanation of why it occurs…</p>
<p> <span id="more-67"></span>
<p>Take a look at the following <a href="http://msdn.microsoft.com/en-us/library/system.windows.dependencyproperty.aspx">DependencyProperty</a> implementation:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">static</span> DependencyProperty ValueProperty =
    DependencyProperty.Register(
        <span class="str">&quot;Value&quot;</span>,
        <span class="kwrd">typeof</span>(<span class="kwrd">double</span>),
        <span class="kwrd">typeof</span>(Window1),
        <span class="kwrd">new</span> PropertyMetadata(0));

<span class="kwrd">public</span> <span class="kwrd">double</span> Value
{
    get { <span class="kwrd">return</span> (<span class="kwrd">double</span>) GetValue(ValueProperty); }
    set { SetValue(ValueProperty, <span class="kwrd">value</span>); }
}</pre>
<p>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>This code looks perfect, and seems to fit the sample perfectly, but it has a very nasty bug.&#160; If you bind to this property, at runtime, you’ll receive:</p>
<p><a href="http://reedcopsey.com/blog/wp-content/uploads/2009/10/XamlParseException.png"><img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="XamlParseException" border="0" alt="XamlParseException" src="http://reedcopsey.com/blog/wp-content/uploads/2009/10/XamlParseException_thumb.png" width="456" height="318" /></a></p>
<p>Drilling into the Exception will show you that the entire StackTrace is System XAML errors.&#160; location is your Window or UserControl’s InitializeComponent() call – not too helpful.</p>
</p>
<p>The InnerException isn’t much better: “Exception has been thrown by the target of an invocation.”&#160; It, too, has a shorter StackTrace full of “CreateInstanceFromType” errors.&#160; Again, not too helpful.</p>
<p>However, the InnerException of that InnerException is more promising: “The type initializer for ‘WpfCSharpApplication.Window1’ threw an exception.”&#160; This exception at least tells us its something that’s happening when we initialize our Window, providing a scope.&#160; (In this case, we already knew this, but still more useful than before.)</p>
<p>This exception, again, has another level of InnerException, and here, finally, we get some meaningful information: “Default value type does not match type of property ‘Value’.”&#160; The StackTrace of this exception is finally more helpful, as well:</p>
<pre>   at System.Windows.DependencyProperty.ValidateDefaultValueCommon(Object defaultValue, Type propertyType, String propertyName, ValidateValueCallback validateValueCallback, Boolean checkThreadAffinity)
   at System.Windows.DependencyProperty.ValidateMetadataDefaultValue(PropertyMetadata defaultMetadata, Type propertyType, String propertyName, ValidateValueCallback validateValueCallback)
   at System.Windows.DependencyProperty.RegisterCommon(String name, Type propertyType, Type ownerType, PropertyMetadata defaultMetadata, ValidateValueCallback validateValueCallback)
   at System.Windows.DependencyProperty.Register(String name, Type propertyType, Type ownerType, PropertyMetadata typeMetadata, ValidateValueCallback validateValueCallback)
   at System.Windows.DependencyProperty.Register(String name, Type propertyType, Type ownerType, PropertyMetadata typeMetadata)
   at WpfCSharpApplication.Window1..cctor() in C:\Users\Reed\Documents\Visual Studio 2008\Projects\TestProjects\WpfCSharpApplication\Window1.xaml.cs:line 12</pre>
<p>Looking at this, we can finally narrow down (after drilling through four levels of exceptions!) that our issue is something to do with the DependencyProperty defined on line 12 – in our case, ValueProperty.&#160; Also, we know that the default value type does not match.</p>
<p>Look again at the ValueProperty declaration:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">static</span> DependencyProperty ValueProperty =
    DependencyProperty.Register(
        <span class="str">&quot;Value&quot;</span>,
        <span class="kwrd">typeof</span>(<span class="kwrd">double</span>),
        <span class="kwrd">typeof</span>(Window1),
        <span class="kwrd">new</span> PropertyMetadata(0));</pre>
<p>We’re declaring and defining this to be of type System.Double [typeof(double) in the second parameter].&#160; We’re also giving it a default value of 0.&#160; Intuitively, this seems fine, but there is a very serious problem here.</p>
<p>The <a href="http://msdn.microsoft.com/en-us/library/ms557329.aspx">constructor for PropertyMetadata</a> we’re using to supply a default value has this declaration:</p>
<pre class="csharpcode"><span class="kwrd">public</span> PropertyMetadata(Object defaultValue)</pre>
<p>In order to handle any type of property, the dependency property system in WPF uses System.Object to pass the default value.&#160; When we pass 0 to the defaultValue parameter, the compiler does the equivalent of the following:</p>
<pre class="csharpcode"><span class="kwrd">int</span> tempValue = 0;
<span class="kwrd">object</span> tempObject = tempValue; <span class="rem">// Box int into System.Object</span>
PropertyMetadata tempMeta = <span class="kwrd">new</span> PropertyMetadata(tempObject);
<span class="rem">// Pass tempMeta into DependencyProperty initializer</span></pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>We’re creating an integer (since a “0” in C# will be handled as an integer), boxing it into an object, and passing that to our PropertyMetadata constructor.&#160; Later, when we bind to this dependency property, the property system sees that the type is a double, and attempts to do something along the lines of:</p>
<pre class="csharpcode"><span class="kwrd">object</span> tempObject = GetValue(ValueProperty); <span class="rem">// Get the object</span>
<span class="kwrd">double</span> <span class="kwrd">value</span> = (<span class="kwrd">double</span>)tempObject;</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>This, unfortunately, fails, throwing an <a href="http://msdn.microsoft.com/en-us/library/system.invalidcastexception.aspx">InvalidCastException</a>, because tempObject is a boxed integer, not a boxed double, and you cannot unbox a value type and cast it to a different value type in a single operation.</p>
<p>This is described in section 4.3.2 of the <a href="http://msdn.microsoft.com/en-us/vcsharp/aa336809.aspx">C# Language Specification</a>:</p>
<pre>For an unboxing conversion to a given non-nullable-value-type to succeed at run-time,
the value of the source operand must be a reference to a boxed value of that
non-nullable-value-type. If the source operand is null, a System.NullReferenceException
is thrown. If the source operand is a reference to an incompatible object, a
System.InvalidCastException is thrown.</pre>
<p>This is demonstrated in this short console program:</p>
<pre class="csharpcode"><span class="kwrd">namespace</span> CSharpConsoleProject
{
     <span class="kwrd">class</span> Program
    {
        <span class="kwrd">static</span> <span class="kwrd">void</span> Main(<span class="kwrd">string</span>[] args)
        {
            <span class="kwrd">int</span> tempInteger = 3;
            System.Object tempObject = tempInteger;

            <span class="rem">// This is, of course, fine, as expected, </span>
            <span class="rem">// because you can implicitly convert from int to double</span>
            <span class="kwrd">double</span> tempDoubleDirect = (<span class="kwrd">double</span>) tempInteger;

            <span class="rem">// This, is also allowed, since it's unboxing into an</span>
            <span class="rem">// System.Int32, then casting to double</span>
            <span class="kwrd">double</span> tempDoubleTwoCasts = (<span class="kwrd">double</span>) (<span class="kwrd">int</span>) tempObject;

            <span class="rem">// This is not allowed.  You cannot unbox and cast in one operation</span>
            <span class="kwrd">double</span> tempDoubleCast = (<span class="kwrd">double</span>) tempObject;
        }
    }
}</pre>
<p>The program above will throw on the last line.&#160; Eric Lippert blogged about this in his post: <a href="http://blogs.msdn.com/ericlippert/archive/2009/03/19/representation-and-identity.aspx">Representation and Identity</a>, and gave a very detailed explanation as to why this is not allowed.</p>
<p>If we apply this to our dependency property declaration, the answer is simple – we just need to force the compiler to treat the default value as the appropriate type (<a href="http://msdn.microsoft.com/en-us/library/678hzkk9.aspx">double</a>), and everything will work fine:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">static</span> DependencyProperty ValueProperty =
    DependencyProperty.Register(
        <span class="str">&quot;Value&quot;</span>,
        <span class="kwrd">typeof</span>(<span class="kwrd">double</span>),
        <span class="kwrd">typeof</span>(Window1),
        <span class="kwrd">new</span> PropertyMetadata(0D));</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>This works because we’ve added the suffix “D” to our integer value, which forces it to treat it as a double.&#160; We could have put in “0.0” instead of “0D”, since literal values with a decimal separator are treated as doubles by default, but I recommend explicitly using the appropriate literal suffix instead.</p>
<p>The issue arises with floating point types other than <a href="http://msdn.microsoft.com/en-us/library/678hzkk9.aspx">double</a>.&#160; If you use a float or decimal, you must specify the suffix “f” or “m”.</p>
<p>Integer types are trickier, since the type chosen depends on the value (it will choose int, uint, long, then ulong, depending on the value).&#160; My recommendation is to always use the integer suffix when using unsigned types, as well as when using short or long types.&#160; This prevents accidental issues which could arise by changing the default value in the future.</p>
]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2009/10/23/wpf-common-dependency-property-exception/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Using a Behavior to Aggregate Values in a Master-Detail view in M-V-VM</title>
		<link>http://reedcopsey.com/2009/10/14/using-a-behavior-to-aggregate-values-in-a-master-detail-view-in-m-v-vm/</link>
		<comments>http://reedcopsey.com/2009/10/14/using-a-behavior-to-aggregate-values-in-a-master-detail-view-in-m-v-vm/#comments</comments>
		<pubDate>Thu, 15 Oct 2009 00:21:37 +0000</pubDate>
		<dc:creator>Reed</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://reedcopsey.com/?p=64</guid>
		<description><![CDATA[It is very difficult to handle situations in a master-detail view, where the master side displays a value derived from aggregating the detail collection. The Model-View-ViewModel pattern makes this even more challenging, since most means of handling this require changing your model, or using extensive code behind. For example, suppose you have a list of [...]]]></description>
			<content:encoded><![CDATA[<p>It is very difficult to handle situations in a master-detail view, where the master side displays a value derived from aggregating the detail collection. The Model-View-ViewModel pattern makes this even more challenging, since most means of handling this require changing your model, or using extensive code behind.</p>
<p> <span id="more-64"></span>
</p>
<p>For example, suppose you have a list of SalesPerson classes, each of which had a list of Sales, and you wanted to display this in a ListView using a GridView.&#160; It would be common to want to display each SalesPerson&#8217;s total sales in the grid, along with their name and other information.</p>
<p>Typical approaches to this rely on handling the data in the code behind.&#160; This is difficult to handle correctly, especially if you want edits in the details section (Sales) to be reflected in the master section in real time.</p>
<p>If, however, the Sales class implements INotifyPropertyChanged, and the list of Sales implements INotifyCollectionChanged or is a BindingList, there is another option.</p>
<p>By taking advantage of INotifyPropertyChanged, you can bind to each element within the collection, and be updated when individual elements change.&#160; INotifyCollectionChanged can be used to track additions or removals from the child collection.&#160; Wrapping this in a class makes tracking changes simple, if you’re just looking at a single SalesPerson at a time.</p>
<p>However, introducing the GridView makes this much more challenging.&#160; Now, you have a CellTemplate for each grid cell which would normally bind to one property of SalesPerson.&#160; Since you’re defining this in a CellTemplate, it’s difficult to setup a custom class and handle binding issues, and life becomes challenging.</p>
<p>The first approach I considered was to use an IValueConverter.&#160; This allows you to bind a TextBlock directly to your collection, providing a converter that would aggregate the values.&#160; This works for initially displaying the values, but doesn’t update if the user changes a value in the details section.&#160; The cell in the master’s grid doesn’t get updated.</p>
<p>Finally, I realized that I could make a custom behavior, which contained the wrapper class that wraps around the collection.&#160; The Behavior itself can bind to the collection, and handle the aggregation.&#160; In order to make this work properly, I also had to make the behavior capable of binding to the associated object’s property; in this case, the Text property of the TextBlock I was using.</p>
<p>By hooking this all together, I was able to make a Master-Detail work, and update in real time:</p>
<p><a href="http://reedcopsey.com/blog/wp-content/uploads/2009/10/aggregator1.png"><img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="Screenshot showing original" border="0" alt="Screenshot showing original" src="http://reedcopsey.com/blog/wp-content/uploads/2009/10/aggregator1_thumb.png" width="620" height="252" /></a> </p>
<p>Starting with the above picture, I can now type values into the Details section, and everything updates in real-time:</p>
<p><a href="http://reedcopsey.com/blog/wp-content/uploads/2009/10/aggregator2.png"><img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="Screenshot showing changes" border="0" alt="Screenshot showing changes" src="http://reedcopsey.com/blog/wp-content/uploads/2009/10/aggregator2_thumb.png" width="620" height="252" /></a> There is a bit too much code to easily fit into this post, so I’ve uploaded the entire solution, fully commented, as a sample on <a href="http://gallery.expression.microsoft.com/en-us/CollectionAggregator" target="_blank">Microsoft Expression Gallery : CollectionAggregator</a>.&#160; All of the code is available on the Gallery for download.</p>
]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2009/10/14/using-a-behavior-to-aggregate-values-in-a-master-detail-view-in-m-v-vm/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using Behaviors to Allow the ViewModel to Manage View Lifetime in M-V-VM</title>
		<link>http://reedcopsey.com/2009/10/09/using-behaviors-to-allow-the-viewmodel-to-manage-view-lifetime-in-m-v-vm/</link>
		<comments>http://reedcopsey.com/2009/10/09/using-behaviors-to-allow-the-viewmodel-to-manage-view-lifetime-in-m-v-vm/#comments</comments>
		<pubDate>Fri, 09 Oct 2009 22:42:48 +0000</pubDate>
		<dc:creator>Reed</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://reedcopsey.com/?p=59</guid>
		<description><![CDATA[One common issue people face in the Model-View-ViewModel pattern is how to cleanly deal with the lifetime of the View from within the ViewModel.&#160; Keeping all of the logic in the ViewModel for preventing the View from closing can be a daunting task, especially at first. After some discussions about controlling the lifetime of the [...]]]></description>
			<content:encoded><![CDATA[<p>One common issue people face in the Model-View-ViewModel pattern is how to cleanly deal with the lifetime of the View from within the ViewModel.&#160; Keeping all of the logic in the ViewModel for preventing the View from closing can be a daunting task, especially at first.</p>
<p> <span id="more-59"></span>
<p>After some discussions about controlling the lifetime of the View without introducing Code Behind in Model-View-ViewModel, I went ahead and created a behavior and sample application demonstrating its use.&#160; I also submitted this to the <a href="http://gallery.expression.microsoft.com/en-us/WindowCloseBehavior" target="_blank">Microsoft Expression Gallery: WindowCloseBehavior</a>.&#160; All of the code is available on the Expression Gallery for download.</p>
<p>The basic idea is to use a Behavior, introduced with Expression Blend 3, to allow the View to hook into commands defined completely within the ViewModel.&#160; By attaching a behavior to your View, and binding to the ViewModel, you can allow the ViewModel to do some very important things:</p>
<ol>
<li>Prevent the View’s Window from closing, even if the user clicks in the “X” at the top of the Window. </li>
<li>Receive notification in the ViewModel when the user tries to close (which allows for “Are you sure?” message boxes, and other similar things) </li>
<li>Receive notification in the ViewModel when the View’s Window has successfully closed </li>
</ol>
<p>How does this work?&#160; First, we need to have our ViewModel provide at least one, and potentially two, ICommand implementations.&#160; The first will bind to the behavior’s CloseCommand property, the second to the CloseFailCommand property.</p>
<p>The first is the Close Command itself.&#160; When the user tries to close the Window, the behavior will use the CloseCommand’s CanExecute() method to determine whether to allow the Window to close.&#160; If CanExecute() returns true, the Window will be allowed to close.&#160; If not, then it will stay open.</p>
<p>If the CloseCommand’s CanExecute() method returns false, and the user bound the Behavior’s CloseFailCommand to an ICommand, it will execute at that point.</p>
<p>If the CloseCommands’s CanExecute() method returns true, the window will be allowed to close.&#160; When the window finally closes, the CloseCommand will be executed.</p>
<p>Using it in code is easy – for example, our MainView (the View in our sample project), just adds this behavior to the main UserControl:</p>
<pre class="csharpcode"><span class="kwrd">&lt;</span><span class="html">UserControl</span> <span class="attr">x:Class</span><span class="kwrd">=&quot;DemonstrateCloseBehavior.MainView&quot;</span>
             <span class="attr">xmlns</span><span class="kwrd">=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;</span>
             <span class="attr">xmlns:x</span><span class="kwrd">=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;</span>
             <span class="attr">xmlns:Interactivity</span><span class="kwrd">=&quot;clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity&quot;</span>
             <span class="attr">xmlns:BehaviorLibrary</span><span class="kwrd">=&quot;clr-namespace:WindowCloseBehavior;assembly=WindowCloseBehavior&quot;</span>
             <span class="attr">Height</span><span class="kwrd">=&quot;Auto&quot;</span> <span class="attr">Width</span><span class="kwrd">=&quot;400&quot;</span> <span class="attr">HorizontalContentAlignment</span><span class="kwrd">=&quot;Center&quot;</span><span class="kwrd">&gt;</span>
  <span class="kwrd">&lt;</span><span class="html">Interactivity:Interaction.Behaviors</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">BehaviorLibrary:WindowCloseBehavior</span> <span class="attr">CloseCommand</span><span class="kwrd">=&quot;{Binding CloseCommand}&quot;</span> <span class="attr">CloseFailCommand</span><span class="kwrd">=&quot;{Binding CloseFailCommand}&quot;</span> <span class="kwrd">/&gt;</span>
  <span class="kwrd">&lt;/</span><span class="html">Interactivity:Interaction.Behaviors</span><span class="kwrd">&gt;</span>
  <span class="kwrd">&lt;</span><span class="html">Grid</span><span class="kwrd">&gt;</span>
  ...</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
</p>
<p>That’s all that has to happen in the View.</p>
<p>The ViewModel, similarly, just needs to provide a couple of commands:</p>
<pre class="csharpcode"><span class="kwrd">public</span> ICommand CloseCommand
{
    get; <span class="kwrd">private</span> set;
 }
<span class="kwrd">public</span> ICommand CloseFailCommand
{
    get; <span class="kwrd">private</span> set;
}</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
</p>
<p>In the sample project, I implemented these by using a custom Command class which takes delegates for Execute and CanExecute:</p>
<pre class="csharpcode"><span class="kwrd">public</span> MainViewModel()
{
    <span class="kwrd">this</span>.CloseCommand = <span class="kwrd">new</span> DelegateCommand(
        () =&gt; MessageBox.Show(<span class="str">&quot;Window close method activated in ViewModel&quot;</span>),
        () =&gt; <span class="kwrd">this</span>.AllowWindowToClose);

    <span class="kwrd">this</span>.CloseFailCommand = <span class="kwrd">new</span> DelegateCommand(
        () =&gt; MessageBox.Show(<span class="str">&quot;Please check the appropriate check box to close this Window.&quot;</span>),
        () =&gt; <span class="kwrd">true</span>);
}</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>This just lets us show messages to the user demonstrating the behavior.</p>
<p>Please feel free to use this as needed, and provide any feedback on its usefulness.</p>
]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2009/10/09/using-behaviors-to-allow-the-viewmodel-to-manage-view-lifetime-in-m-v-vm/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>System.WeakReference internals and side-effects</title>
		<link>http://reedcopsey.com/2009/07/08/systemweakreference-internals-and-side-effects/</link>
		<comments>http://reedcopsey.com/2009/07/08/systemweakreference-internals-and-side-effects/#comments</comments>
		<pubDate>Wed, 08 Jul 2009 23:33:41 +0000</pubDate>
		<dc:creator>Reed</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://reedcopsey.com/?p=50</guid>
		<description><![CDATA[After discussing the uses of WeakReference, I decided to dig into the internal implementation in .NET a bit more.  I thought I’d write a short bit about how the WeakReference class works internally, and some side effects of using this vs. a standard strong reference. First off, I’m going to in general ignore long weak [...]]]></description>
			<content:encoded><![CDATA[<p>After discussing the uses of WeakReference, I decided to dig into the internal implementation in .NET a bit more.  I thought I’d write a short bit about how the WeakReference class works internally, and some side effects of using this vs. a standard strong reference.</p>
<p><span id="more-50"></span></p>
<p>First off, I’m going to in general ignore long weak references.  They behave very similarly to short weak references, in terms of usage.  (The difference is in whether or not the object is reachable after finalization, but prior to reclaiming the memory itself.)  I have yet to find a use for them to be necessary, and nearly everything I’ve read suggests completely avoiding them.</p>
<p>Secondly, I’d like to credit Jeffrey Richter’s <a href="http://msdn.microsoft.com/en-us/magazine/bb985011.aspx" target="_blank">excellent article on memory management</a> for much of the details of how the CLR handles weak references internally.</p>
<p>That being said, when you create a short weak reference, a few things happen.  First, a new object (the WeakReference) class is constructed with your object.  The WeakReference instance internally stores an IntPtr to a <a href="http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.gchandle.aspx" target="_blank">GCHandle</a> which is allocated with <a href="http://msdn.microsoft.com/en-us/library/83y4ak54.aspx" target="_blank">GCHandleType.Weak</a> (or WeakTrackRessurection for long weak references).  The WeakReference then drops the strong handle to your object.</p>
<p>This is where the magic happens…</p>
<p>The CLR takes this GCHandle, and maintains an internal table of weak references.  This is a separately maintained list of handles in the runtime.  When a garbage collection happens, the GC builds a full graph of the objects rooted within your application.  Prior to doing any cleanup, the weak reference table is scanned, and any references found which point to an object outside of the GC graph are marked as null.  However, your WeakReference instance still points to this same location in the WeakReference table.</p>
<p>When you use a WeakReference, a few things happen.  Upon accessing WeakReference.Target, the WeakReference class checks to see if the handle pointed to by it’s IntPtr is IntPtr.Zero.  This will be true any time the object has been collected.  This is why you must always check for null – the entire point of a WeakReference is to allow the GC to cleanup your object if it wants to, but you don’t know when or if that’s happened.  If it’s not, it then asks the GC to retrieve the “real” object associated with the WeakReference’s GCHandle, and sets it to a System.Object reference.  This strongly references the object, which will now prevent it from being collected.  It then returns the new object.  Provided you use the returned object in some fashion, you’ll keep that strong reference, which will keep the object rooted, so it will not be collected.</p>
<p>After you’re completely done with it, the WeakReference gets finalized, at which point the table entry is cleared and available for use by another weak reference in the future.</p>
<p>Now, the important part – what does this mean in terms of using WeakReferences in our applications?  Any time we use WeakReference instead of a standard, strong reference, a couple of things will happen.  One, we’re going to have the extra overhead associated with allocating a separate object (the WeakReference) which contains an IntPtr and a boolean (to track whether it’s a short or long reference).  Second, any time we access the WeakReference.Target property, we’re effectively doing two null checks plus a method call on a GCHandle to retrieve our “real” object.  In addition, we’re going to have to add extra logic on our end to test for whether the WeakReference is pointing to an object that’s been collected.  In addition, the GC is going to have one more reference to check each time it does a GC.</p>
<p>There is definitely overhead involved in this, but surprisingly, it’s fairly minor – less than many property accessors used in common patterns.  This is great news, especially considering how common the usage of WeakReference is becoming… Although it may not be realized, these are frequently used internally throughout the BCL, especially in Windows Presentation Foundation, since WeakReferences are a core element of data binding in WPF.</p>
]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2009/07/08/systemweakreference-internals-and-side-effects/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
 