<?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>Arrange Act Assert &#187; WPF</title> <atom:link href="http://www.arrangeactassert.com/category/wpf/feed/" rel="self" type="application/rss+xml" /><link>http://www.arrangeactassert.com</link> <description>Jag Reehal on Agile Development, ASP.NET MVC and all manner of good stuff</description> <lastBuildDate>Thu, 24 Nov 2011 00:01:20 +0000</lastBuildDate> <language>en</language> <sy:updatePeriod>hourly</sy:updatePeriod> <sy:updateFrequency>1</sy:updateFrequency> <generator>http://wordpress.org/?v=3.3.1</generator> <xhtml:meta xmlns:xhtml="http://www.w3.org/1999/xhtml" name="robots" content="noindex" /> <item><title>How to use DesignData to populate controls with design time data in Silverlight and WPF</title><link>http://www.arrangeactassert.com/how-to-use-designdata-to-populate-controls-with-design-time-data-in-silverlight-and-wpf/</link> <comments>http://www.arrangeactassert.com/how-to-use-designdata-to-populate-controls-with-design-time-data-in-silverlight-and-wpf/#comments</comments> <pubDate>Fri, 06 Aug 2010 00:00:52 +0000</pubDate> <dc:creator>Jag Reehal</dc:creator> <category><![CDATA[Silverlight]]></category> <category><![CDATA[WPF]]></category><guid
isPermaLink="false">http://www.arrangeactassert.com/?p=1217</guid> <description><![CDATA[In this post I’ll be showing how you can use DesignData to populate controls when you’re designing Silverlight or WPF applications in Expression Blend or Visual Studio. The image below shows a user control in Expression Blend which allows users take part in a poll to find out what their favorite colors of the rainbow [...]]]></description> <content:encoded><![CDATA[<p>In this post I’ll be showing how you can use DesignData to populate controls when you’re designing Silverlight or WPF applications in Expression Blend or Visual Studio.</p><p>The image below shows a user control in Expression Blend which allows users take part in a poll to find out what their favorite colors of the rainbow are.</p><p><img
src="http://www.arrangeactassert.com/wp-content/themes/resources/images/ExpressionBlendWithoutDesignTimeData.png" alt="Expression Blend Without Design Time Data" /></p><p>As you can see it’s difficult if not impossible to imagine what we are actually designing here.</p><p>The user control doesn’t look any better in Visual Studio 2010.</p><p><img
src="http://www.arrangeactassert.com/wp-content/themes/resources/images/VisualStudioWithoutDesignTimeData.png" alt="Visual Studio Without Design Time Data" /></p><h3 class="subheading">Creating the ViewModel for the Object Data Source</h3><p>The code for the ViewModel we want to create sample data for is shown below.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public class ViewModel : INotifyPropertyChanged
{
    private string _name;

    public event PropertyChangedEventHandler PropertyChanged;

    public string Name
    {
        get { return _name; }
        set
        {
            _name = value;
            OnPropertyChanged(&quot;Name&quot;);
        }
    }

    public ObservableCollection&lt;RainbowColor&gt; RainbowColors { get; set; }

    protected void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this,
                new PropertyChangedEventArgs(propertyName));
        }
    }
}

public class RainbowColor
{
    public string Description { get; set; }
    public string Color { get; set; }
}
</pre><h3 class="subheading">The bit where Expression Blend flexes it muscles</h3><p>If you&#8217;re using Expression Blend the good news is that creating sample data can be done in a couple of clicks.</p><p>In the Data tab click on the &#8216;Create data source&#8217; button to see the following window</p><p><img
src="http://www.arrangeactassert.com/wp-content/themes/resources/images/CreatingObjectDataSourceInExpressionBlend.png" alt="Expression Blend Without Design Time Data" /></p><p>Next select ViewModel as the object to create the data source for</p><p><img
src="http://www.arrangeactassert.com/wp-content/themes/resources/images/ChoosingTheObjectForTheDataSourceInExpressionBlend.png" alt="Expression Blend Without Design Time Data" /></p><p>This will create a XAML file populated with sample data, which has been modified to be the colors of the rainbow.</p><pre class="brush: xml; gutter: false; title: ; toolbar: true; notranslate">
&lt;DeginTimeDataInSilverlightApplications:ViewModel
    xmlns:DeginTimeDataInSilverlightApplications=&quot;clr-namespace:DeginTimeDataInSilverlightApplications&quot;
    Name=&quot;Roy G Biv&quot;&gt;
	&lt;DeginTimeDataInSilverlightApplications:ViewModel.RainbowColors&gt;
        &lt;DeginTimeDataInSilverlightApplications:RainbowColor Color=&quot;#FFFF0000&quot; Description=&quot;Red&quot;/&gt;
        &lt;DeginTimeDataInSilverlightApplications:RainbowColor Color=&quot;#FFFFA500&quot; Description=&quot;Orange&quot;/&gt;
        &lt;DeginTimeDataInSilverlightApplications:RainbowColor Color=&quot;#FFFFFF00&quot; Description=&quot;Yellow&quot;/&gt;
        &lt;DeginTimeDataInSilverlightApplications:RainbowColor Color=&quot;#FF008000&quot; Description=&quot;Green&quot;/&gt;
        &lt;DeginTimeDataInSilverlightApplications:RainbowColor Color=&quot;#FF0000FF&quot; Description=&quot;Blue&quot;/&gt;
        &lt;DeginTimeDataInSilverlightApplications:RainbowColor Color=&quot;#FF4B0082&quot; Description=&quot;Indigo&quot;/&gt;
        &lt;DeginTimeDataInSilverlightApplications:RainbowColor Color=&quot;#FFEE82EE&quot; Description=&quot;Violet&quot;/&gt;
    &lt;/DeginTimeDataInSilverlightApplications:ViewModel.RainbowColors&gt;
&lt;/DeginTimeDataInSilverlightApplications:ViewModel&gt;
</pre><h3 class="subheading">Creating DesignData in Visual Studio</h3><p>In Visual Studio you have to create the XAML file manually and change the build action for it to <strong>DesignData</strong> as shown below.</p><p><img
src="http://www.arrangeactassert.com/wp-content/themes/resources/images/VisualStudioBuildActionForDesignTimeData.png" alt="Visual Studio BuildAction For DesignTimeData" /></p><p>My recommendation is to store the XAML files containing sample data in a SampleData sub folder (which Expression Blend does by default).</p><h3 class="subheading">Setting the DataContext to use DesignData in XAML</h3><p>In order to bind the sample data to the user control during design time we need to add a few more lines in the opening tag.</p><p>The lines that use DesignData to bind data in the designer are highlighted in the XAML for the user control below.</p><pre class="brush: xml; gutter: false; highlight: [5,6,7,8]; title: ; toolbar: true; notranslate">
&lt;UserControl
	xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
	xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
	x:Class=&quot;DeginTimeDataInSilverlightApplications.MainPage&quot;
	xmlns:mc=&quot;http://schemas.openxmlformats.org/markup-compatibility/2006&quot;
	mc:Ignorable=&quot;d&quot;
	xmlns:d=&quot;http://schemas.microsoft.com/expression/blend/2008&quot;
	d:DataContext=&quot;{d:DesignData Source=./SampleData/ViewModelSampleData.xaml}&quot;
	d:DesignWidth=&quot;600&quot;&gt;
    &lt;UserControl.Resources&gt;
        &lt;DataTemplate x:Key=&quot;RainbowTemplate&quot;&gt;
            &lt;Border Background=&quot;{Binding Color}&quot;&gt;
                &lt;StackPanel Margin=&quot;10&quot; Orientation=&quot;Horizontal&quot;&gt;
                    &lt;CheckBox/&gt;
                    &lt;TextBlock Text=&quot;{Binding Description}&quot;
                               Foreground=&quot;Black&quot;
                               FontWeight=&quot;Bold&quot; /&gt;
                &lt;/StackPanel&gt;
            &lt;/Border&gt;
        &lt;/DataTemplate&gt;
        &lt;Style x:Key=&quot;ListBoxStretchStyle&quot; TargetType=&quot;ListBoxItem&quot;&gt;
            &lt;Setter Property=&quot;HorizontalContentAlignment&quot; Value=&quot;Stretch&quot;/&gt;
        &lt;/Style&gt;
    &lt;/UserControl.Resources&gt;
    &lt;Grid x:Name=&quot;LayoutRoot&quot; Background=&quot;White&quot;&gt;
        &lt;StackPanel&gt;
            &lt;TextBlock Text=&quot;Choose your favorite colors!&quot;
                       Margin=&quot;5&quot;
                       TextAlignment=&quot;Center&quot;
FontWeight=&quot;Bold&quot; /&gt;
            &lt;Grid&gt;
                &lt;Grid.ColumnDefinitions&gt;
                    &lt;ColumnDefinition Width=&quot;Auto&quot;/&gt;
                    &lt;ColumnDefinition Width=&quot;*&quot;/&gt;
                    &lt;ColumnDefinition Width=&quot;Auto&quot;/&gt;
                &lt;/Grid.ColumnDefinitions&gt;
                &lt;TextBlock Text=&quot;Name:&quot; Margin=&quot;10&quot; VerticalAlignment=&quot;Center&quot; /&gt;
                &lt;TextBox Text=&quot;{Binding Name}&quot;  Grid.Column=&quot;1&quot;  VerticalAlignment=&quot;Center&quot;/&gt;
                &lt;Button Content=&quot;Submit&quot; Grid.Column=&quot;2&quot; Margin=&quot;10&quot;  Width=&quot;100&quot; Height=&quot;50&quot;/&gt;
            &lt;/Grid&gt;
			&lt;ListBox ItemsSource=&quot;{Binding RainbowColors}&quot;
					 ItemContainerStyle=&quot;{StaticResource ListBoxStretchStyle}&quot;
					 ItemTemplate=&quot;{StaticResource RainbowTemplate}&quot;/&gt;
        &lt;/StackPanel&gt;
    &lt;/Grid&gt;
&lt;/UserControl&gt;
</pre><p>Pay attention to the line</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
mc:Ignorable=&quot;d&quot;
</pre><p>If you don’t add this you will see the following error when you try to compile the solution</p><p><strong>XAML Namespace http://schemas.microsoft.com/expression/blend/2008 is not resolved.</strong></p><p>If you’re using Expression Blend the designer will now look like this</p><p><img
src="http://www.arrangeactassert.com/wp-content/themes/resources/images/ExpressionBlendWithDesignTimeData.png" alt="Expression Blend With Design Time Data" /></p><p>or like this if you&#8217;re using Visual Studio 2010</p><p><img
src="http://www.arrangeactassert.com/wp-content/themes/resources/images/VisualStudioWithDesignTimeData.png" alt="Visual Studio With Design Time Data" /></p><h3 class="subheading">Does it matter if I’m using MVVM or not?</h3><p>No.  Even though I’m using a ViewModel in this example, all that matters is that you can bind your sample data to the data context of the control.</p> ]]></content:encoded> <wfw:commentRss>http://www.arrangeactassert.com/how-to-use-designdata-to-populate-controls-with-design-time-data-in-silverlight-and-wpf/feed/</wfw:commentRss> <slash:comments>6</slash:comments> </item> <item><title>How design time data will save you time designing Silverlight and WPF applications</title><link>http://www.arrangeactassert.com/how-design-time-data-will-save-you-time-designing-silverlight-and-wpf-applications/</link> <comments>http://www.arrangeactassert.com/how-design-time-data-will-save-you-time-designing-silverlight-and-wpf-applications/#comments</comments> <pubDate>Fri, 06 Aug 2010 00:00:26 +0000</pubDate> <dc:creator>Jag Reehal</dc:creator> <category><![CDATA[Silverlight]]></category> <category><![CDATA[SketchFlow]]></category> <category><![CDATA[WPF]]></category><guid
isPermaLink="false">http://www.arrangeactassert.com/?p=1180</guid> <description><![CDATA[When it comes to designing applications it’s definitely a lot easier when you can visualize what you’re creating without actually running the solution. So why should it be any different for Silverlight and WPF? If you just want to know how you can populate controls during design time the links below show three (of the [...]]]></description> <content:encoded><![CDATA[<p>When it comes to designing applications it’s definitely a lot easier when you can visualize what you’re creating without actually running the solution.</p><p>So why should it be any different for Silverlight and WPF?</p><p>If you just want to know how you can populate controls during design time the links below show three (of the many) ways you can populate your pages, windows, user controls, grids etc with sample data in Expression Blend or Visual Studio.</p><ul><li><a
href="http://www.arrangeactassert.com/how-to-use-a-designinstance-to-populate-controls-with-design-time-data-in-silverlight-and-wpf">How to use a designinstance to populate controls with design time data in Silverlight and WPF</a></li><p><br/></p><li><a
href="http://www.arrangeactassert.com/how-to-use-designdata-to-populate-controls-with-design-time-data-in-silverlight-and-wpf">How to use DesignData to populate controls with design time data in Silverlight and WPF</a></li><p><br/></p><li><a
href="http://www.arrangeactassert.com/how-to-use-the-designerproperties-isindesigntool-property-to-populate-controls-with-design-time-data-in-silverlight-using-Expression-Blend">How to use the DesignerProperties.IsInDesignTool property to populate controls with design time data in Silverlight</a></li><p><br/></p><li><a
href="http://www.arrangeactassert.com/how-to-use-the-DesignerProperties-GetIsInDesignMode-method-to-populate-controls-with-design-time-data-in-wpf-using-Expression-Blend">How to use the DesignerProperties.GetIsInDesignMode method to populate controls with design time data in WPF</a></li></ul><h3 class="subheading">Why populating controls with design time data in Silverlight and WPF will improve your productivity</h3><p>Let’s image for a moment we were given the task of designing a Silverlight application to find out what colors of the rainbow are the most popular.</p><p>The SketchFlow prototype below shows what we are aiming for.</p><p><img
src="http://www.arrangeactassert.com/wp-content/themes/resources/images/RainbowInSketchflow.png" alt="Rainbow in Sketchflow" /></p><p>Well this is easy enough isn’t it?  The XAML below should do the job.</p><pre class="brush: xml; gutter: false; title: ; toolbar: true; notranslate">
&lt;UserControl
	xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
	xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
	x:Class=&quot;DeginTimeDataInSilverlightApplications.MainPage&quot;
    Width=&quot;600&quot;&gt;
    &lt;UserControl.Resources&gt;
        &lt;DataTemplate x:Key=&quot;RainbowTemplate&quot;&gt;
            &lt;Border Background=&quot;{Binding Color}&quot;&gt;
                &lt;StackPanel Margin=&quot;10&quot; Orientation=&quot;Horizontal&quot;&gt;
                    &lt;CheckBox/&gt;
                    &lt;TextBlock Text=&quot;{Binding Description}&quot;
							   Foreground=&quot;Black&quot;
							   FontWeight=&quot;Bold&quot; /&gt;
                &lt;/StackPanel&gt;
            &lt;/Border&gt;
        &lt;/DataTemplate&gt;
    &lt;/UserControl.Resources&gt;
    &lt;Grid x:Name=&quot;LayoutRoot&quot; Background=&quot;White&quot;&gt;
		&lt;StackPanel&gt;
			&lt;TextBlock Text=&quot;Choose your favorite colors!&quot;
					   Margin=&quot;5&quot;
					   TextAlignment=&quot;Center&quot;
                       FontWeight=&quot;Bold&quot; /&gt;
			&lt;Grid&gt;
				&lt;Grid.ColumnDefinitions&gt;
					&lt;ColumnDefinition Width=&quot;Auto&quot;/&gt;
					&lt;ColumnDefinition Width=&quot;*&quot;/&gt;
					&lt;ColumnDefinition Width=&quot;Auto&quot;/&gt;
				&lt;/Grid.ColumnDefinitions&gt;
				&lt;TextBlock Text=&quot;Name:&quot;
                           Margin=&quot;10&quot;
                           VerticalAlignment=&quot;Center&quot; /&gt;
				&lt;TextBox Text=&quot;{Binding Name}&quot;
                         Grid.Column=&quot;1&quot;
                         VerticalAlignment=&quot;Center&quot;/&gt;
				&lt;Button Content=&quot;Submit&quot;
                        Grid.Column=&quot;2&quot;
                        Margin=&quot;10&quot;
                        Width=&quot;100&quot;
                        Height=&quot;50&quot;/&gt;
			&lt;/Grid&gt;
			&lt;ListBox ItemsSource=&quot;{Binding RainbowColors}&quot;
                     ItemTemplate=&quot;{StaticResource RainbowTemplate}&quot;/&gt;
		&lt;/StackPanel&gt;
	&lt;/Grid&gt;
&lt;/UserControl&gt;
</pre><p>Spot any problems, issues or flaws yet?</p><p>If we run this application this is what is shown to the user.</p><p><img
src="http://www.arrangeactassert.com/wp-content/themes/resources/images/RainbowWithoutStretch.png" alt="Rainbow Without Stretch" /></p><p>As you can see there is a problem with the ListBoxItem not stretching to the width of the grid.</p><p>If you had used deign time data this is what you would have seen in Expression Blend.</p><p><img
src="http://www.arrangeactassert.com/wp-content/themes/resources/images/SketchflowShowingRainbowWithoutStretch.png" alt="Showing Rainbow Without Stretch" /></p><h3 class="subheading">Still not convinced design time data will help you?</h3><p>Well in that case have fun implementing a fix, running the application, implementing another fix, running the application again until you’ve resolved the issue or ran out of time.</p><h3 class="subheading">Jag Reehal’s Final Thought on ‘How design time data will save you time designing Silverlight and WPF applications’</h3><p>Designing is so much easier when you’re able to see controls populated with sample data because you will be able to find and resolve design issues and problems quicker using design time data.</p> ]]></content:encoded> <wfw:commentRss>http://www.arrangeactassert.com/how-design-time-data-will-save-you-time-designing-silverlight-and-wpf-applications/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>How to use a DesignInstance to populate controls with design time data in Silverlight and WPF</title><link>http://www.arrangeactassert.com/how-to-use-a-designinstance-to-populate-controls-with-design-time-data-in-silverlight-and-wpf/</link> <comments>http://www.arrangeactassert.com/how-to-use-a-designinstance-to-populate-controls-with-design-time-data-in-silverlight-and-wpf/#comments</comments> <pubDate>Fri, 06 Aug 2010 00:00:17 +0000</pubDate> <dc:creator>Jag Reehal</dc:creator> <category><![CDATA[Silverlight]]></category> <category><![CDATA[WPF]]></category><guid
isPermaLink="false">http://www.arrangeactassert.com/?p=1185</guid> <description><![CDATA[In this post I&#8217;ll be showing how you can use a DesignInstance to populate controls when you’re designing Silverlight or WPF applications in Expression Blend or Visual Studio. The image below shows a user control in Expression Blend which allows users take part in a poll to find out what their favorite colors of the [...]]]></description> <content:encoded><![CDATA[<p>In this post I&#8217;ll be showing how you can use a DesignInstance to populate controls when you’re designing Silverlight or WPF applications in Expression Blend or Visual Studio.</p><p>The image below shows a user control in Expression Blend which allows users take part in a poll to find out what their favorite colors of the rainbow are.</p><p><img
src="http://www.arrangeactassert.com/wp-content/themes/resources/images/ExpressionBlendWithoutDesignTimeData.png" alt="Expression Blend Without Design Time Data" /></p><p>As you can see it’s difficult if not impossible to imagine what we are actually designing here.</p><p>The user control doesn’t look any better in Visual Studio 2010.</p><p><img
src="http://www.arrangeactassert.com/wp-content/themes/resources/images/VisualStudioWithoutDesignTimeData.png" alt="Visual Studio  WithoutDesign Time Data" /></p><h3 class="subheading">Creating the ViewModel to bind the data context using DesignInstance</h3><p>The code below shows the DesignTimeViewModel class to be used as the data context during design time.  It inherits from the ViewModel class which will be used when the application is actually running.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public class DesignTimeViewModel : ViewModel
{
    public DesignTimeViewModel()
    {
        Name = &quot;Roy G Biv&quot;;
        RainbowColors = new ObservableCollection&lt;RainbowColor&gt;()
                            {
                                new RainbowColor() {Description = &quot;Red&quot;, Color =  &quot;#FFFF0000&quot;},
                                new RainbowColor() {Description = &quot;Orange&quot;, Color =  &quot;#FFFFA500&quot;},
                                new RainbowColor() {Description = &quot;Yellow&quot;, Color =  &quot;#FFFFFF00&quot;},
                                new RainbowColor() {Description = &quot;Green&quot;, Color =  &quot;#FF008000&quot;},
                                new RainbowColor() {Description = &quot;Blue&quot;, Color =  &quot;#FF0000FF&quot;},
                                new RainbowColor() {Description = &quot;Indigo&quot;, Color =  &quot;#FF4B0082&quot;},
                                new RainbowColor() {Description = &quot;Violet&quot;, Color =  &quot;#FFEE82EE&quot;}
                            };
    }
}

public class ViewModel : INotifyPropertyChanged
{
    private string _name;

    public event PropertyChangedEventHandler PropertyChanged;

    public string Name
    {
        get { return _name; }
        set
        {
            _name = value;
            OnPropertyChanged(&quot;Name&quot;);
        }
    }

    public ObservableCollection&lt;RainbowColor&gt; RainbowColors { get; set; }

    protected void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this,
                new PropertyChangedEventArgs(propertyName));
        }
    }
}

public class RainbowColor
{
    public string Description { get; set; }
    public string Color { get; set; }
}
</pre><h3 class="subheading">Setting the DataContext to use DesignInstance in XAML</h3><p>In order to bind the DesignTimeViewModel to the user control during design time we need to add a few more lines in the opening tag.</p><p>The lines that use a DesignInstance to bind data in the designer are highlighted in the XAML for the user control below.</p><pre class="brush: xml; gutter: false; highlight: [5,6,7,8,9]; title: ; toolbar: true; notranslate">
 &lt;UserControl
	xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
	xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
	x:Class=&quot;DeginTimeDataInSilverlightApplications.MainPage&quot;
	xmlns:mc=&quot;http://schemas.openxmlformats.org/markup-compatibility/2006&quot;
	mc:Ignorable=&quot;d&quot;
	xmlns:d=&quot;http://schemas.microsoft.com/expression/blend/2008&quot;
	xmlns:local=&quot;clr-namespace:DeginTimeDataInSilverlightApplications&quot;
    d:DataContext=&quot;{d:DesignInstance Type=local:DesignTimeViewModel,IsDesignTimeCreatable=True}&quot;
    d:DesignWidth=&quot;600&quot;&gt;
    &lt;UserControl.Resources&gt;
        &lt;DataTemplate x:Key=&quot;RainbowTemplate&quot;&gt;
            &lt;Border Background=&quot;{Binding Color}&quot;&gt;
                &lt;StackPanel Margin=&quot;10&quot; Orientation=&quot;Horizontal&quot;&gt;
                    &lt;CheckBox/&gt;
                    &lt;TextBlock Text=&quot;{Binding Description}&quot;
                               Foreground=&quot;Black&quot;
                               FontWeight=&quot;Bold&quot; /&gt;
                &lt;/StackPanel&gt;
            &lt;/Border&gt;
        &lt;/DataTemplate&gt;
        &lt;Style x:Key=&quot;ListBoxStretchStyle&quot; TargetType=&quot;ListBoxItem&quot;&gt;
            &lt;Setter Property=&quot;HorizontalContentAlignment&quot; Value=&quot;Stretch&quot;/&gt;
        &lt;/Style&gt;
    &lt;/UserControl.Resources&gt;
    &lt;Grid x:Name=&quot;LayoutRoot&quot; Background=&quot;White&quot;&gt;
        &lt;StackPanel&gt;
            &lt;TextBlock Text=&quot;Choose your favorite colors!&quot;
                       Margin=&quot;5&quot;
                       TextAlignment=&quot;Center&quot;
                       FontWeight=&quot;Bold&quot; /&gt;
            &lt;Grid&gt;
                &lt;Grid.ColumnDefinitions&gt;
                    &lt;ColumnDefinition Width=&quot;Auto&quot;/&gt;
                    &lt;ColumnDefinition Width=&quot;*&quot;/&gt;
                    &lt;ColumnDefinition Width=&quot;Auto&quot;/&gt;
                &lt;/Grid.ColumnDefinitions&gt;
                &lt;TextBlock Text=&quot;Name:&quot; Margin=&quot;10&quot; VerticalAlignment=&quot;Center&quot; /&gt;
                &lt;TextBox Text=&quot;{Binding Name}&quot;  Grid.Column=&quot;1&quot;  VerticalAlignment=&quot;Center&quot;/&gt;
                &lt;Button Content=&quot;Submit&quot; Grid.Column=&quot;2&quot; Margin=&quot;10&quot;  Width=&quot;100&quot; Height=&quot;50&quot;/&gt;
            &lt;/Grid&gt;
            &lt;ListBox ItemsSource=&quot;{Binding RainbowColors}&quot;
					 ItemContainerStyle=&quot;{StaticResource ListBoxStretchStyle}&quot;
					 ItemTemplate=&quot;{StaticResource RainbowTemplate}&quot;/&gt;
        &lt;/StackPanel&gt;
    &lt;/Grid&gt;
&lt;/UserControl&gt;
</pre><p>Pay attention to the line</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
mc:Ignorable=&quot;d&quot;
</pre><p>If you don’t add this you will see the following error when you try to compile the solution</p><p><strong>XAML Namespace http://schemas.microsoft.com/expression/blend/2008 is not resolved.</strong></p><p>If you’re using Expression Blend the designer will now look like this</p><p><img
src="http://www.arrangeactassert.com/wp-content/themes/resources/images/ExpressionBlendWithDesignTimeData.png" alt="Expression Blend With Design Time Data" /></p><p>or like this if you&#8217;re using Visual Studio 2010</p><p><img
src="http://www.arrangeactassert.com/wp-content/themes/resources/images/VisualStudioWithDesignTimeData.png" alt="Visual Studio With Design Time Data" /></p><h3 class="subheading">Does it matter if I’m using MVVM or not?</h3><p>No.  Even though I’m using a ViewModel in this example, all that matters is that you can bind your sample data to the data context of the control.</p> ]]></content:encoded> <wfw:commentRss>http://www.arrangeactassert.com/how-to-use-a-designinstance-to-populate-controls-with-design-time-data-in-silverlight-and-wpf/feed/</wfw:commentRss> <slash:comments>3</slash:comments> </item> <item><title>How to use the DesignerProperties.GetIsInDesignMode method to populate controls with design time data in WPF using Expression Blend</title><link>http://www.arrangeactassert.com/how-to-use-the-designerproperties-getisindesignmode-method-to-populate-controls-with-design-time-data-in-wpf-using-expression-blend/</link> <comments>http://www.arrangeactassert.com/how-to-use-the-designerproperties-getisindesignmode-method-to-populate-controls-with-design-time-data-in-wpf-using-expression-blend/#comments</comments> <pubDate>Fri, 06 Aug 2010 00:00:04 +0000</pubDate> <dc:creator>Jag Reehal</dc:creator> <category><![CDATA[WPF]]></category><guid
isPermaLink="false">http://www.arrangeactassert.com/?p=1318</guid> <description><![CDATA[In this post I’ll be showing how you can use the DesignerProperties.GetIsInDesignMode method to populate controls when you’re designing WPF applications in Expression Blend. This solution does not work in Visual Studio 2010. To find out about what options do work in Visual Studio check out the following posts: How to use a designinstance to [...]]]></description> <content:encoded><![CDATA[<p>In this post I’ll be showing how you can use the DesignerProperties.GetIsInDesignMode method to populate controls when you’re designing WPF applications in Expression Blend.</p><p>This solution does not work in Visual Studio 2010.  To find out about what options do work in Visual Studio check out the following posts:</p><ul><li><a
href="http://www.arrangeactassert.com/how-to-use-a-designinstance-to-populate-controls-with-design-time-data-in-silverlight-and-wpf">How to use a designinstance to populate controls with design time data in Silverlight and WPF</a></li><li><a
href="http://www.arrangeactassert.com/how-to-use-designdata-to-populate-controls-with-design-time-data-in-silverlight-and-wpf">How to use DesignData to populate controls with design time data in Silverlight and WPF</a></li></ul><p>If you&#8217;re looking for a Silverlight solution using DesignerProperties check out the post &#8216;<a
href="http://www.arrangeactassert.com/how-to-use-the-designerproperties-isindesigntool-property-to-populate-controls-with-design-time-data-in-silverlight-using-Expression-Blend">How to use the DesignerProperties.IsInDesignTool property to populate controls with design time data in Silverlight</a>&#8216;</p><p>The image below shows a user control in Expression Blend which allows users take part in a poll to find out what their favorite colors of the rainbow are.</p><p><img
src="http://www.arrangeactassert.com/wp-content/themes/resources/images/WPFExpressionBlendWithoutDesignTimeData.png" alt="Expression Blend Without Design Time Data" /></p><p>As you can see it’s difficult if not impossible to imagine what we are actually designing here.</p><h3 class="subheading">Creating a ViewModelProvider a.k.a ViewModel ServiceLocator</h3><p>Essentially what we want is to use a ViewModel populated with sample data during design time and the actual ViewModel when the application is running.</p><p>To do this we can use the ViewModel and DesignTimeViewModel classes shown below.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public class ViewModel : INotifyPropertyChanged
{
    private string _name;

    public event PropertyChangedEventHandler PropertyChanged;

    public string Name
    {
        get { return _name; }
        set
        {
            _name = value;
            OnPropertyChanged(&quot;Name&quot;);
        }
    }

    public ObservableCollection&lt;RainbowColor&gt; RainbowColors { get; set; }

    protected void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this,
                new PropertyChangedEventArgs(propertyName));
        }
    }
}

public class DesignTimeViewModel : ViewModel
{
    public DesignTimeViewModel()
    {
        Name = &quot;Roy G Biv&quot;;
        RainbowColors = new ObservableCollection&lt;RainbowColor&gt;()
                        {
                            new RainbowColor() {Description = &quot;Red&quot;, Color =  &quot;#FFFF0000&quot;},
                            new RainbowColor() {Description = &quot;Orange&quot;, Color =  &quot;#FFFFA500&quot;},
                            new RainbowColor() {Description = &quot;Yellow&quot;, Color =  &quot;#FFFFFF00&quot;},
                            new RainbowColor() {Description = &quot;Green&quot;, Color =  &quot;#FF008000&quot;},
                            new RainbowColor() {Description = &quot;Blue&quot;, Color =  &quot;#FF0000FF&quot;},
                            new RainbowColor() {Description = &quot;Indigo&quot;, Color =  &quot;#FF4B0082&quot;},
                            new RainbowColor() {Description = &quot;Violet&quot;, Color =  &quot;#FFEE82EE&quot;}
                        };
    }
}

public class RainbowColor
{
    public string Description { get; set; }
    public string Color { get; set; }
}
</pre><p>A provider/service locater class allows Expression Blend to determine which ViewModel to use.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public class ViewModelProvider
{
    public ViewModel ViewModel
    {
        get
        {
            if (DesignerProperties.GetIsInDesignMode(new DependencyObject()))
            {
                return new DesignTimeViewModel();
            }
            return new ViewModel();
        }
    }
}
</pre><h3 class="subheading">Setting the DataContext to use the ViewModelProvider in XAML</h3><p>In order to bind the sample data to the user control during design time we need to add a line in the opening tag, create a resource and set the data context to use the ViewModel returned by the provider/service locator.</p><p>The lines to do this are highlighted in the XAML for the user control below.</p><pre class="brush: xml; gutter: false; highlight: [7,23,25,26,27]; title: ; toolbar: true; notranslate">
&lt;Window
	xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
	xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
	x:Class=&quot;RainbowWpfApplication.MainWindow&quot;
	x:Name=&quot;Window&quot;
	Title=&quot;MainWindow&quot;
	xmlns:local=&quot;clr-namespace:RainbowWpfApplication&quot;
	Width=&quot;600&quot;&gt;
	&lt;Window.Resources&gt;
		&lt;DataTemplate x:Key=&quot;RainbowTemplate&quot;&gt;
			&lt;Border Background=&quot;{Binding Color}&quot;&gt;
				&lt;StackPanel Margin=&quot;10&quot; Orientation=&quot;Horizontal&quot;&gt;
					&lt;CheckBox/&gt;
					&lt;TextBlock Text=&quot;{Binding Description}&quot;
							   Foreground=&quot;Black&quot;
							   FontWeight=&quot;Bold&quot; /&gt;
				&lt;/StackPanel&gt;
			&lt;/Border&gt;
		&lt;/DataTemplate&gt;
		&lt;Style x:Key=&quot;ListBoxStretchStyle&quot; TargetType=&quot;ListBoxItem&quot;&gt;
			&lt;Setter Property=&quot;HorizontalContentAlignment&quot; Value=&quot;Stretch&quot;/&gt;
		&lt;/Style&gt;
		&lt;local:ViewModelProvider x:Key=&quot;ViewModelProvider&quot; /&gt;
	&lt;/Window.Resources&gt;
	&lt;Window.DataContext&gt;
		&lt;Binding Source=&quot;{StaticResource ViewModelProvider}&quot; Path=&quot;ViewModel&quot;/&gt;
	&lt;/Window.DataContext&gt;
	&lt;Grid x:Name=&quot;LayoutRoot&quot; Background=&quot;White&quot;&gt;
		&lt;StackPanel Margin=&quot;0,0,0,145&quot;&gt;
			&lt;TextBlock Text=&quot;Choose your favorite colors!&quot;
					   Margin=&quot;5&quot;
					   TextAlignment=&quot;Center&quot;
					   FontWeight=&quot;Bold&quot; /&gt;
			&lt;Grid&gt;
				&lt;Grid.ColumnDefinitions&gt;
					&lt;ColumnDefinition Width=&quot;Auto&quot;/&gt;
					&lt;ColumnDefinition Width=&quot;*&quot;/&gt;
					&lt;ColumnDefinition Width=&quot;Auto&quot;/&gt;
				&lt;/Grid.ColumnDefinitions&gt;
				&lt;TextBlock Text=&quot;Name:&quot; Margin=&quot;10&quot; VerticalAlignment=&quot;Center&quot; /&gt;
				&lt;TextBox Text=&quot;{Binding Name}&quot;  Grid.Column=&quot;1&quot;  VerticalAlignment=&quot;Center&quot;/&gt;
				&lt;Button Content=&quot;Submit&quot; Grid.Column=&quot;2&quot; Margin=&quot;10&quot;  Width=&quot;100&quot; Height=&quot;50&quot;/&gt;
			&lt;/Grid&gt;
			&lt;ListBox ItemsSource=&quot;{Binding RainbowColors}&quot;
					 ItemContainerStyle=&quot;{StaticResource ListBoxStretchStyle}&quot;
					 ItemTemplate=&quot;{StaticResource RainbowTemplate}&quot;/&gt;
		&lt;/StackPanel&gt;
	&lt;/Grid&gt;
&lt;/Window&gt;
</pre><p>The Expression Blend designer will now look like this</p><p><img
src="http://www.arrangeactassert.com/wp-content/themes/resources/images/WPFExpressionBlendWithDesignTimeData.png" alt="Expression Blend With Design Time Data" /></p><h3 class="subheading">Does it matter if I’m using MVVM or not?</h3><p>No.  Even though I’m using a ViewModel in this example, all that matters is that you can bind your sample data to the data context of the control.</p> ]]></content:encoded> <wfw:commentRss>http://www.arrangeactassert.com/how-to-use-the-designerproperties-getisindesignmode-method-to-populate-controls-with-design-time-data-in-wpf-using-expression-blend/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Using IDataErrorInfo for validation in MVVM with Silverlight and WPF</title><link>http://www.arrangeactassert.com/using-idataerrorinfo-for-validation-in-mvvm-with-silverlight-and-wpf/</link> <comments>http://www.arrangeactassert.com/using-idataerrorinfo-for-validation-in-mvvm-with-silverlight-and-wpf/#comments</comments> <pubDate>Tue, 06 Jul 2010 23:01:57 +0000</pubDate> <dc:creator>Jag Reehal</dc:creator> <category><![CDATA[MVVM]]></category> <category><![CDATA[Silverlight]]></category> <category><![CDATA[Unit tests]]></category> <category><![CDATA[WPF]]></category><guid
isPermaLink="false">http://www.arrangeactassert.com/?p=968</guid> <description><![CDATA[In this post we will be looking at how validation can be done by implementing the IDataErrorInfo interface for a calculator we have been building as part of the Silverlight refactoring series. The IDataErrorInfo interface gives you the ability to do validation without throwing exceptions. The full solution for this post can be downloaded here. [...]]]></description> <content:encoded><![CDATA[<p>In this post we will be looking at how validation can be done by implementing the <a
href="http://msdn.microsoft.com/en-us/library/system.componentmodel.idataerrorinfo.aspx">IDataErrorInfo</a> interface for a calculator we have been building as part of the <a
href="http://www.arrangeactassert.com/how-to-refactor-and-build-better-microsoft-silverlight-applications/">Silverlight refactoring series</a>.</p><p>The IDataErrorInfo interface gives you the ability to do validation without throwing exceptions.</p><p>The full solution for this post can be downloaded <a
href="http://cid-8a29bf85dc9538dc.office.live.com/self.aspx/.Public/Silverlight%20Demos/SilverlightCalculator/SilverlightCalculatorValidationIDataErrorInfo.zip">here</a>.</p><h3 class="subheading">Pre IDataErrorInfo</h3><p>As you can see in the code below we are throwing exceptions in the setters for the two values we want to add together.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public string  FirstValue
{
    get { return _firstValue; }
    set
    {
        _firstValue = value;
        try
        {
            int.Parse(_firstValue);
        }
        catch (Exception)
        {
            throw new Exception(&quot;That's not a number&quot;);
        }
        OnPropertyChanged(&quot;FirstValue&quot;);
    }
}
public string  SecondValue
{
    get { return _secondValue; }
    set
    {
        _secondValue = value;
        try
        {
            int.Parse(_secondValue);
        }
        catch (Exception)
        {
            throw new Exception(&quot;That's not a number&quot;);
        }
        OnPropertyChanged(&quot;SecondValue&quot;);
    }
}
</pre><h3 class="subheading">Implementing the IDataErrorInfo interface</h3><p>The IDataErrorInfo interface consists of two properties.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
string this[string columnName] {get;}
string Error {get;}
</pre><p>For the Error property we can just return null because we don’t want to return a single error message for the entire object.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public string Error
{
    get { return null; }
}
</pre><p>For the property which returns an error for a text box we <strong>could</strong> do the validation like this</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public string this[string columnName]
{
    get
    {
        string error = null;
        switch (columnName)
        {
            case &quot;FirstValue&quot;:
                try
                {
                    int.Parse(_firstValue);
                }
                catch (Exception)
                {
                    error = &quot;That is not a number&quot;;
                }
                break;
            case &quot;SecondValue&quot;:
                try
                {
                    int.Parse(_firstValue);
                }
                catch (Exception)
                {
                    error = &quot;That is not a number&quot;;
                }
                break;
        }
        return error;
    }
}
</pre><p>But as we saw in a previous post <a
href="http://www.arrangeactassert.com/enabling-buttons-in-silverlight-and-wpf-using-mvvm-and-validatesonexceptions/">about using ValidatesOnExceptions to do validation</a> it’s much easier to write unit tests when there are separation of concerns and the ViewModel is not responsible for validation.</p><p>So this means we need to create a class for storing the validation error for each textbox</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public class ValidationBase
{
    public readonly Dictionary&lt;string, string&gt; Errors;

    public ValidationBase()
    {
        Errors = new Dictionary&lt;string, string&gt;();
    }

    public void AddError(string propertyName, string message)
    {
        if (!Errors.ContainsKey(propertyName))
        {
            Errors[propertyName] = message;
        }
    }

    public void RemoveErrors(string propertyName)
    {
        Errors.Remove(propertyName);
    }

    public string GetErrorMessageForProperty(string propertyName)
    {
        string message;
        Errors.TryGetValue(propertyName, out message);
        return message;
    }

    public bool HasErrors()
    {
        return Errors.Count != 0;
    }
}
</pre><p>which is inherited by a CalculatorValidator class that returns a boolean value if the property value is not valid</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
[Export(typeof(ICalculatorValidator))]
public class CalculatorValidator : ValidationBase, ICalculatorValidator
{
    [ImportMany]
    public IEnumerable&lt;ICalculatorValidationRule&gt; CalculatorValidationRules { get; set; }

    public bool IsPropertyValid(string propertyName, string value)
    {
        RemoveErrors(propertyName);
        foreach (var calculatorValidationRule in CalculatorValidationRules)
        {
            if (!calculatorValidationRule.IsValid(value))
            {
                AddError(propertyName, calculatorValidationRule.ErrorMessage);
                return false;
            }
        }
        return true;
    }
}
</pre><p>If you’re new to the series the validation rules for calculator are being imported by MEF.  Read how and why we are doing this in the &#8216;<a
href="http://www.arrangeactassert.com/applying-the-open-closed-principle-in-silverlight-and-wpf-using-mef/">Applying the Open Closed Principle in Silverlight and WPF using MEF</a>&#8216; post.</p><p>Now we can inject/import the CalculatorValidator into the ViewModel and use it to validate the users input.</p><p>As we only want the user to be able to click the calculate button when the form is valid we call we the CheckIfCalculteButtonShouldBeEnabled method when a text box value has changed.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
[Export]
public class CalculatorViewModel : INotifyPropertyChanged, IDataErrorInfo
{
    private string _firstValue;
    private string _secondValue;
    private string _result;

    private readonly ICalculator _calculator;
    private readonly RelayCommand _calculateCommand;

    public event PropertyChangedEventHandler PropertyChanged;
    private readonly ICalculatorValidator _calculatorValidator;

    [ImportingConstructor]
    public CalculatorViewModel(ICalculator calculator, ICalculatorValidator calculatorValidator)
    {
        _calculator = calculator;
        _calculatorValidator = calculatorValidator;
        _calculateCommand = new RelayCommand(Calculate) { IsEnabled = true };

        _firstValue = &quot;0&quot;;
        _secondValue = &quot;0&quot;;
    }
    public void Calculate()
    {
        Result = _calculator.Add(Convert.ToInt32(FirstValue), Convert.ToInt32(SecondValue)).ToString();
    }

    public string FirstValue
    {
        get { return _firstValue; }
        set
        {
            _firstValue = value;
            OnPropertyChanged(&quot;FirstValue&quot;);
        }
    }

    public string SecondValue
    {
        get { return _secondValue; }
        set
        {
            _secondValue = value;
            OnPropertyChanged(&quot;SecondValue&quot;);
        }
    }

    public void CheckIfCalculteButtonShouldBeEnabled()
    {
        _calculateCommand.IsEnabled = _calculatorValidator.HasErrors() == false;
    }

    public string Result
    {
        get { return _result; }
        private set
        {
            _result = value;
            OnPropertyChanged(&quot;Result&quot;);
        }
    }

    public RelayCommand CalculateCommand
    {
        get { return _calculateCommand; }
    }

    protected void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this,
                new PropertyChangedEventArgs(propertyName));
        }
    }

    public string this[string columnName]
    {
        get
        {
            string error = null;
            switch (columnName)
            {
                case &quot;FirstValue&quot;:
                    error = ValidateNumber(&quot;FirstValue&quot;, _firstValue);
                    break;
                case &quot;SecondValue&quot;:
                    error = ValidateNumber(&quot;SecondValue&quot;, _secondValue);
                    break;
            }

            CheckIfCalculteButtonShouldBeEnabled();
            return error;
        }
    }

    public string ValidateNumber(string propertyName, string value)
    {
        if (!_calculatorValidator.IsPropertyValid(propertyName, value))
        {
            return _calculatorValidator.GetErrorMessageForProperty(propertyName);
        }
        return null;
    }

    public string Error
    {
        get { return null; }
    }
}
</pre><p>The code below shows how we can unit test the ViewModel which implements the IDataErrorInfo interface.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
[TestFixture]
public class When_using_the_CalculatorViewModel
{
    private Mock&lt;ICalculator&gt; _calculator;
    private Mock&lt;ICalculatorValidator&gt; _calculatorValidator;
    private CalculatorViewModel _calculatorViewModel;

    [SetUp]
    public void SetUp()
    {
        _calculator = new Mock&lt;ICalculator&gt;();
        _calculatorValidator = new Mock&lt;ICalculatorValidator&gt;();
        _calculatorViewModel = new CalculatorViewModel(_calculator.Object, _calculatorValidator.Object);
    }

    [Test]
    public void Initial_value_of_first_number_is_0()
    {
        // Arrange
        // checking initial value

        // Act
        var result = _calculatorViewModel.FirstValue;

        // Assert
        result.ShouldEqual(&quot;0&quot;);
    }

    [Test]
    public void Initial_value_of_second_number_is_0()
    {
        // Arrange
        // checking initial value

        // Act
        var result = _calculatorViewModel.SecondValue;

        // Assert
        result.ShouldEqual(&quot;0&quot;);
    }

    [Test]
    public void Initial_value_of_calculate_button_is_enabled()
    {
        // Arrange
        // checking initial value

        // Act
        var result = _calculatorViewModel.CalculateCommand.IsEnabled;

        // Assert
        result.ShouldBeTrue();
    }

    [Test]
    public void ValidateNumber_returns_null_if_value_is_valid()
    {
        // Arrange
        _calculatorValidator.Setup(c =&gt; c.IsPropertyValid(&quot;X&quot;,&quot;X&quot;)).Returns(true);

        // Act
        var result = _calculatorViewModel.ValidateNumber(&quot;X&quot;,&quot;X&quot;);

        // Assert
        result.ShouldBeNull();
    }

    [Test]
    public void ValidateNumber_returns_error_message_if_value_is_not_valid()
    {
        // Arrange
        const string errorMessage = &quot;ErrorMessageText&quot;;
        _calculatorValidator.Setup(c =&gt; c.IsPropertyValid(&quot;X&quot;, &quot;X&quot;)).Returns(false);
        _calculatorValidator.Setup(c =&gt; c.GetErrorMessageForProperty(&quot;X&quot;)).Returns(errorMessage);

        // Act
        var result = _calculatorViewModel.ValidateNumber(&quot;X&quot;, &quot;X&quot;);

        // Assert
        result.ShouldEqual(errorMessage);
    }

    [Test]
    public void Calculate_command_should_not_be_enabled_if_ViewModel_is_not_valid()
    {
        // Arrange
        _calculatorValidator.Setup(c =&gt; c.HasErrors()).Returns(true);

        // Act
        _calculatorViewModel.CheckIfCalculteButtonShouldBeEnabled();

        // Assert
        _calculatorViewModel.CalculateCommand.IsEnabled.ShouldBeFalse();
    }

    [Test]
    public void Calculate_command_should_be_enabled_if_ViewModel_is_valid()
    {
        // Arrange
        _calculatorValidator.Setup(c =&gt; c.HasErrors()).Returns(false);

        // Act
        _calculatorViewModel.CheckIfCalculteButtonShouldBeEnabled();

        // Assert
        _calculatorViewModel.CalculateCommand.IsEnabled.ShouldBeTrue();
    }
}
</pre><p>The final change we need to make is to change the text box binding to ValidatesOnDataErrors=True in the XAML file.</p><pre class="brush: xml; gutter: false; title: ; toolbar: true; notranslate">
&lt;TextBox Text=&quot;{Binding FirstValue, Mode=TwoWay, ValidatesOnDataErrors=True}&quot;/&gt;
&lt;TextBox Text=&quot;{Binding SecondValue, Mode=TwoWay, ValidatesOnDataErrors=True}&quot;/&gt;
</pre><h3 class="subheading">So what have we achieved?</h3><p>In this post we have refactored the code to use the IDataErrorInfo interface and are no longer throwing exceptions to do validation.</p><p>Whether you choose to use it or not depends if you want multiple errors for a single property to be combined into a single error message.</p> ]]></content:encoded> <wfw:commentRss>http://www.arrangeactassert.com/using-idataerrorinfo-for-validation-in-mvvm-with-silverlight-and-wpf/feed/</wfw:commentRss> <slash:comments>10</slash:comments> </item> <item><title>Enabling buttons in Silverlight and WPF using MVVM and ValidatesOnExceptions</title><link>http://www.arrangeactassert.com/enabling-buttons-in-silverlight-and-wpf-using-mvvm-and-validatesonexceptions/</link> <comments>http://www.arrangeactassert.com/enabling-buttons-in-silverlight-and-wpf-using-mvvm-and-validatesonexceptions/#comments</comments> <pubDate>Mon, 05 Jul 2010 23:10:40 +0000</pubDate> <dc:creator>Jag Reehal</dc:creator> <category><![CDATA[Moq]]></category> <category><![CDATA[MVVM]]></category> <category><![CDATA[Silverlight]]></category> <category><![CDATA[Unit tests]]></category> <category><![CDATA[WPF]]></category><guid
isPermaLink="false">http://www.arrangeactassert.com/?p=957</guid> <description><![CDATA[In a previous post we saw how exceptions could be used for Silverlight validation. While could validate the users input using exceptions, it wasn’t possible to disable the calculate button if the input values were invalid (because they were either blank or non-numeric). The code used in this post can be downloaded here. So how [...]]]></description> <content:encoded><![CDATA[<p>In a <a
href=" Validation in Silverlight and WPF using ValidatesOnExceptions">previous post we saw how exceptions</a> could be used for Silverlight validation.</p><p>While could validate the users input using exceptions, it wasn’t possible to disable the calculate button if the input values were invalid (because they were either blank or non-numeric).</p><p>The code used in this post can be downloaded <a
href="http://cid-8a29bf85dc9538dc.office.live.com/self.aspx/.Public/Silverlight%20Demos/SilverlightCalculator/SilverlightCalculatorValidationUsingExceptions.zip">here</a>.</p><h3 class="subheading">So how are we going to solve the problem?</h3><p>Throughout the Silverlight refactoring series I’ve tried to illustrate how important <a
href="http://en.wikipedia.org/wiki/Solid_(object-oriented_design)">SOLID design principles</a> are for having testable applications.</p><p>So if we think about the ViewModel, we need to ask ourselves if it’s the right place or should be responsible for validation?</p><p>In this case I would say no.</p><h3 class="subheading">When should the button be enabled?</h3><blockquote><p>For a calculate button to be enabled, both text boxes must contain numeric values</p></blockquote><p>This means we have to know if both text boxes are valid <strong>at the same time</strong>.  Taking a step back here, let&#8217;s think about the bigger picture.</p><p>What if there are three or four text boxes?</p><p>What we really after is a class that will be responsible for knowing if any text boxes are invalid.</p><p>This can be done by using a validation base class.</p><p>In the code below notice how the ValidationBase class <strong>doesn&#8217;t</strong> know anything about enabling or disabling the calculate button.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public class ValidationBase
{
    public readonly Dictionary&lt;string, string&gt; Errors;

    public ValidationBase()
    {
        Errors = new Dictionary&lt;string, string&gt;();
    }

    public void AddError(string propertyName, string message)
    {
        if (!Errors.ContainsKey(propertyName))
        {
            Errors[propertyName] = message;
        }
    }

    public void RemoveErrors(string propertyName)
    {
        Errors.Remove(propertyName);
    }

    public bool IsPropertyValid(string propertyName)
    {
        return !Errors.ContainsKey(propertyName);
    }

    public string GetErrorMessageForProperty(string propertyName)
    {
        string message;
        Errors.TryGetValue(propertyName, out message);
        return message;
    }

    public bool IsValid()
    {
        return Errors.Count == 0;
    }
}
</pre><p>The code below shows the unit tests for the ValidationBase class.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
[TestFixture]
public class When_using_the_ValidatiorBase
{
    private ValidationBase _validationBase;

    [SetUp]
    public void SetUp()
    {
        _validationBase = new ValidationBase();
    }

    [Test]
    public void IsValid_should_return_false_when_errors_exist()
    {
        // Arrange
        _validationBase.AddError(&quot;propertyName&quot;, &quot;message&quot;);

        // Act
        var result = _validationBase.IsValid();

        // Assert
        result.ShouldBeFalse();
    }

    [Test]
    public void IsValid_should_return_true_when_no_errors_exist()
    {
        // Arrange
        // collection will be empty at this point

        // Act
        var result = _validationBase.IsValid();

        // Assert
        result.ShouldBeTrue();
    }

    [Test]
    public void IsPropertyValid_should_return_false_if_error_exists()
    {
        // Arrange
        _validationBase.AddError(&quot;propertyName&quot;, &quot;message&quot;);

        // Act
        var result = _validationBase.IsPropertyValid(&quot;propertyName&quot;);

        // Assert
        result.ShouldBeFalse();
    }

    [Test]
    public void IsPropertyValid_should_return_true_if_error_does_not_exist()
    {
        // Arrange
        // collection will be empty at this point

        // Act
        var result = _validationBase.IsPropertyValid(&quot;X&quot;);

        // Assert
        result.ShouldBeTrue();
    }

    [Test]
    public void Should_be_able_to_return_message_for_error()
    {
        // Arrange
        _validationBase.AddError(&quot;propertyName&quot;, &quot;message&quot;);

        // Act
        var result = _validationBase.GetErrorMessageForProperty(&quot;propertyName&quot;);

        // Assert
        result.ShouldEqual(&quot;message&quot;);
    }

    [Test]
    public void Should_return_null_if_message_does_not_exist_for_error()
    {
        // Arrange
        // collection will be empty at this point

        // Act
        var result = _validationBase.GetErrorMessageForProperty(&quot;propertyName&quot;);

        // Assert
        result.ShouldBeNull();
    }
}
</pre><h3 class="subheading">Validating the users input</h3><p>There are three outcomes when validating what the user has entered:</p><ul><li>The value is blank</li><li>The value is not a number</li><li>The value is a number</li></ul><p>All the ViewModel wants to know is if the users input is valid, choosing the appropriate error message isn&#8217;t its concern.  This means we need a class that will be responsible for validation and returning the relevant message.</p><p>For this we will use the CalculatorValidator class we created in the &#8216;<a
href="http://www.arrangeactassert.com/applying-the-open-closed-principle-in-silverlight-and-wpf-using-mef/">Applying the Open Closed Principle in Silverlight and WPF using MEF</a>&#8216; post.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
[Export(typeof(ICalculatorValidator))]
public class CalculatorValidator : ValidationBase, ICalculatorValidator
{
    [ImportMany]
    public IEnumerable&lt;ICalculatorValidationRule&gt; CalculatorValidationRules { get; set; }

    public void ValidateNumber(string propertyName, string value)
    {
        RemoveErrors(propertyName);

        foreach (var calculatorValidationRule in CalculatorValidationRules)
        {
            if (!calculatorValidationRule.IsValid(value))
            {
                AddError(propertyName, calculatorValidationRule.ErrorMessage);
                return;
            }
        }
    }
}
</pre><p>This is useful because if we decide to change how to validate the user&#8217;s input neither the CalculatorValidator or the ViewModel classes need to be modified.</p><h3 class="subheading">Hooking it all up</h3><p>To use the CalculatorValidator in the ViewModel it has to be injected/imported.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
[ImportingConstructor]
public CalculatorViewModel(ICalculator calculator, ICalculatorValidator calculatorValidator)
{
    _calculator = calculator;
    _calculatorValidator = calculatorValidator;
    ...
}
</pre><p>Each time a user enters a value in the text boxes the CheckIfNumberIsValid method checks if the calculate button should be enabled and throws an exception if the users value is not valid.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public string FirstValue
{
    get { return _firstValue; }
    set
    {
        CheckIfNumberIsValid(&quot;FirstValue&quot;, out _firstValue, value);
    }
}

public string SecondValue
{
    get { return _secondValue; }
    set
    {
        CheckIfNumberIsValid(&quot;SecondValue&quot;, out _secondValue, value);
    }
}

public void CheckIfNumberIsValid(string propertyName, out string propertyValue, string value)
{
    _calculatorValidator.ValidateNumber(propertyName, value);

    CheckIfCalculteButtonShouldBeEnabled();

    if (_calculatorValidator.IsPropertyValid(propertyName))
    {
        propertyValue = value;
        OnPropertyChanged(propertyName);
    }
    else
    {
        throw new Exception(_calculatorValidator.GetErrorMessageForProperty(propertyName));
    }
}

public void CheckIfCalculteButtonShouldBeEnabled()
{
    _calculateCommand.IsEnabled = _calculatorValidator.IsValid();
}
</pre><h3 class="subheading">Unit testing the ViewModel in MVVM</h3><p>By using <a
href="http://code.google.com/p/moq/">Moq</a> we can unit test the ViewModel to ensure the button is enabled when there are no validation errors and not enabled when there are validation errors.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
[TestFixture]
public class When_using_the_CalculatorViewModel
{
    private Mock&lt;ICalculator&gt; _calculator;
    private Mock&lt;ICalculatorValidator&gt; _calculatorValidator;
    private CalculatorViewModel _calculatorViewModel;

    [SetUp]
    public void SetUp()
    {
        _calculator = new Mock&lt;ICalculator&gt;();
        _calculatorValidator = new Mock&lt;ICalculatorValidator&gt;();
        _calculatorViewModel = new CalculatorViewModel(_calculator.Object, _calculatorValidator.Object);
    }

    [Test]
    public void Initial_value_of_first_number_is_0()
    {
        // Arrange
        // checking initial value

        // Act
        var result = _calculatorViewModel.FirstValue;

        // Assert
        result.ShouldEqual(&quot;0&quot;);
    }

    [Test]
    public void Initial_value_of_second_number_is_0()
    {
        // Arrange
        // checking initial value

        // Act
        var result = _calculatorViewModel.SecondValue;

        // Assert
        result.ShouldEqual(&quot;0&quot;);
    }

    [Test]
    public void Initial_value_of_calculate_button_is_enabled()
    {
        // Arrange
        // checking initial value

        // Act
        var result = _calculatorViewModel.CalculateCommand.IsEnabled;

        // Assert
        result.ShouldBeTrue();
    }

    [Test]
    [ExpectedException(typeof(Exception))]
    public void Will_throw_exception_if_input_is_invalid()
    {
        // Arrange
        string propertyValue;
        _calculatorValidator.Setup(c =&gt; c.IsPropertyValid(&quot;X&quot;)).Throws(new Exception());

        // Act
        _calculatorViewModel.CheckIfNumberIsValid(&quot;X&quot;, out propertyValue, &quot;X&quot;);

        // Assert
        // should throw exception
    }

    [Test]
    public void Will_set_property_value_if_input_is_valid()
    {
        // Arrange
        string propertyValue;
        _calculatorValidator.Setup(c =&gt; c.IsPropertyValid(&quot;X&quot;)).Returns(true);

        // Act
        _calculatorViewModel.CheckIfNumberIsValid(&quot;X&quot;, out propertyValue, &quot;11&quot;);

        // Assert
        propertyValue.ShouldEqual(&quot;11&quot;);

    }

    [Test]
    public void Calculate_command_should_not_be_enabled_if_ViewModel_is_not_valid()
    {
        // Arrange
        _calculatorValidator.Setup(c =&gt; c.IsValid()).Returns(false);

        // Act
        _calculatorViewModel.CheckIfCalculteButtonShouldBeEnabled();

        // Assert
        _calculatorViewModel.CalculateCommand.IsEnabled.ShouldBeFalse();
    }

    [Test]
    public void Calculate_command_should_be_enabled_if_ViewModel_is_valid()
    {
        // Arrange
        _calculatorValidator.Setup(c =&gt; c.IsValid()).Returns(true);

        // Act
        _calculatorViewModel.CheckIfCalculteButtonShouldBeEnabled();

        // Assert
        _calculatorViewModel.CalculateCommand.IsEnabled.ShouldBeTrue();
    }
}
</pre><h3 class="subheading">So what have we achieved?</h3><p>By using a validation base class we are able to store validation errors and can determine if the controls on the page are all valid.</p><p>The ViewModel can take advantage of this functionality and use it to enable and disable the calculate button.</p><p>Using exceptions for validation isn&#8217;t every developers cup of tea, so be sure to keep an eye on the <a
href="http://www.arrangeactassert.com/how-to-refactor-and-build-better-microsoft-silverlight-applications/">Silverlight refactoring series</a> to see other approaches we can take to do validation in Silverlight 4.</p> ]]></content:encoded> <wfw:commentRss>http://www.arrangeactassert.com/enabling-buttons-in-silverlight-and-wpf-using-mvvm-and-validatesonexceptions/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Validation in Silverlight and WPF using ValidatesOnExceptions</title><link>http://www.arrangeactassert.com/validation-in-silverlight-and-wpf-using-validatesonexceptions/</link> <comments>http://www.arrangeactassert.com/validation-in-silverlight-and-wpf-using-validatesonexceptions/#comments</comments> <pubDate>Wed, 30 Jun 2010 23:43:06 +0000</pubDate> <dc:creator>Jag Reehal</dc:creator> <category><![CDATA[Silverlight]]></category> <category><![CDATA[WPF]]></category><guid
isPermaLink="false">http://www.arrangeactassert.com/?p=941</guid> <description><![CDATA[With the application as it is the user is able to enter non-numeric values and add them together. Clicking the calculate button to add two non-numeric values together will cause the application to do nothing and the user will have no idea why. Try it for yourself here. It would be common sense to validate [...]]]></description> <content:encoded><![CDATA[<p>With the application as it is the user is able to enter non-numeric values and add them together.</p><p>Clicking the calculate button to add two non-numeric values together will cause the application to do nothing and the user will have no idea why.</p><p>Try it for yourself <a
href="http://www.arrangeactassert.com/wp-content/themes/resources/SilverlightDemos/CalculatorDemo/CalculatorDemo.html">here</a>.</p><p>It would be common sense to validate what the user has entered and let them know if and what the problem is.</p><h3 class="subheading">What I&#8217;ve seen most beginners do for validation in Silverlight and WPF</h3><p>One of easiest way (in terms of the amount of code you have to write) to do validation in Silverlight and WPF is to use exceptions.</p><p>To do this we need to make changes in the ViewModel and the Calculator XAML file.</p><p>In the ViewModel an exception needs to be thrown when the input value cannot be converted to a number.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public string FirstValue
{
    get { return _firstValue; }
    set
    {
        _firstValue = value;
        try
        {
            int.Parse(_firstValue);
        }
        catch (Exception)
        {
            throw;
        }
        OnPropertyChanged(&quot;FirstValue&quot;);
    }
}
</pre><p>In the XAML file we set ValidatesOnExceptions equal to true for the text box binding.</p><pre class="brush: xml; gutter: false; title: ; toolbar: true; notranslate">
&lt;TextBox Grid.Column=&quot;0&quot; Text=&quot;{Binding FirstValue, Mode=TwoWay, ValidatesOnExceptions=True}&quot; Height=&quot;25&quot; TextAlignment=&quot;Right&quot;/&gt;
</pre><p>The screenshot below shows what happens if the user does not enter a number into the text box.</p><p><img
src="http://www.arrangeactassert.com/wp-content/themes/resources/images/blog/DefaultSilverlightException.png" alt="Default Silverlight Exception" /></p><p>As you can see error message isn&#8217;t very user friendly.</p><p>To resolve this issue we could set the message of the exception thrown when parsing a number but we would be repeating/duplicating code when validating the SecondValue.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public string FirstValue
{
    get { return _firstValue; }
    set
    {
        _firstValue = value;
        try
        {
            int.Parse(_firstValue);
        }
        catch (Exception)
        {
            throw new Exception(&quot;That's not a number&quot;);
        }
        OnPropertyChanged(&quot;FirstValue&quot;);
    }
}

public string SecondValue
{
    get { return _secondValue; }
    set
    {
        _secondValue = value;
        try
        {
            int.Parse(_firstValue);
        }
        catch (Exception)
        {
            throw new Exception(&quot;That's not a number&quot;);
        }
        OnPropertyChanged(&quot;SecondValue&quot;);
    }
}
</pre><h3 class="subheading">Silverlight validations the <a
href="http://en.wikipedia.org/wiki/Don%27t_repeat_yourself">Don&#8217;t Repeat Yourself</a> Way</h3><p>A better way would to do this is by creating a reusable method for validating the users input.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
void ValidateNumber(string value)
{
    try
    {
        int.Parse(value);
    }
    catch (Exception)
    {
        throw new Exception(&quot;That's not a number&quot;);
    }
}
</pre><p>which could be used like this</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public string FirstValue
{
    get { return _firstValue; }
    set
    {
        _firstValue = value;
        ValidateNumber(value);
        OnPropertyChanged(&quot;FirstValue&quot;);
    }
}

public string SecondValue
{
    get { return _secondValue; }
    set
    {
        _secondValue = value;
        ValidateNumber(value);
        OnPropertyChanged(&quot;SecondValue&quot;);
    }
}
</pre><p>Now when a user enters an invalid number the they would see an error that looks like this</p><p><img
src="http://www.arrangeactassert.com/wp-content/themes/resources/images/blog/CustomSilverlightException.png" alt="Custom Silverlight Exception" /></p><h3 class="subheading">So what have we achieved?</h3><p>With a few lines of code we are able to validate the users input and let them know what the problem is if it&#8217;s not valid.</p><p>If you have arrived here from a search engine, this post is part of series about <a
href="http://www.arrangeactassert.com/how-to-refactor-and-build-better-microsoft-silverlight-applications/">refactoring Silverlight applications</a>.</p><p>So if you’re thinking, this is all very well but the user is still able to click the calculate button even if they have entered invalid values to add together, see how this can prevented in the next part of the series.</p> ]]></content:encoded> <wfw:commentRss>http://www.arrangeactassert.com/validation-in-silverlight-and-wpf-using-validatesonexceptions/feed/</wfw:commentRss> <slash:comments>3</slash:comments> </item> <item><title>Applying the Open Closed Principle in Silverlight and WPF using MEF</title><link>http://www.arrangeactassert.com/applying-the-open-closed-principle-in-silverlight-and-wpf-using-mef/</link> <comments>http://www.arrangeactassert.com/applying-the-open-closed-principle-in-silverlight-and-wpf-using-mef/#comments</comments> <pubDate>Mon, 28 Jun 2010 23:27:39 +0000</pubDate> <dc:creator>Jag Reehal</dc:creator> <category><![CDATA[MEF]]></category> <category><![CDATA[Silverlight]]></category> <category><![CDATA[WPF]]></category><guid
isPermaLink="false">http://www.arrangeactassert.com/?p=900</guid> <description><![CDATA[In this post I want to show how MEF can be used to apply the Open Closed Principle where a class is open for extension but closed for modification. In the Calculator application we have been building as part of the Silverlight refactoring series we could have used the code below to validate a users [...]]]></description> <content:encoded><![CDATA[<p>In this post I want to show how <a
href="http://mef.codeplex.com/">MEF</a> can be used to apply the <a
href="http://en.wikipedia.org/wiki/Open/closed_principle">Open Closed Principle</a> where a class is open for extension but closed for modification.</p><p>In the Calculator application we have been building as part of the <a
href="http://www.arrangeactassert.com/how-to-refactor-and-build-better-microsoft-silverlight-applications/">Silverlight refactoring series</a> we could have used the code below to validate a users input.</p><p>By the way we are throwing exceptions because the application is using ValidatesOnExceptions.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public class CalculatorValidator
{
    public void ValidateNumber(string value)
    {
        if (String.IsNullOrEmpty(value))
        {
            throw new Exception(&quot;Please enter a number&quot;);
        }

        int number;
        if (!int.TryParse(value, out number))
        {
            throw new Exception(&quot;That's not a number&quot;);
        }
    }
}
</pre><p>If we wanted to add more validation rules to check the value cannot be negative or greater than a hundred we have to modify the CalculatorValidator class with two additional if statements.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public class CalculatorValidator
{
    public void ValidateNumber(string value)
    {
        if (String.IsNullOrEmpty(value))
        {
            throw new Exception(&quot;Please enter a number&quot;);
        }

        int number;
        if (!int.TryParse(value, out number))
        {
            throw new Exception(&quot;That's not a number&quot;);
        }

        if (number &lt; 0)
        {
            throw new Exception(&quot;Number cannot be negative&quot;);
        }

        if (number &gt; 100)
        {
            throw new Exception(&quot;That number is too big!&quot;);
        }
    }
}
</pre><p>and this pattern would continue every time you added a new rule, leaving the code as maintainable and stable as a wobbly tower!</p><h3 class="subheading">Implementing the Open Closed Principle</h3><p>Lets start by creating an interface for a validation rule</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public interface ICalculatorValidationRule
{
    bool IsValid(string number);
    string ErrorMessage { get; }
}
</pre><p>Next we create a class for each validation rule by implementing the ICalculatorValidationRule interface</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
[Export(typeof(ICalculatorValidationRule))]
public class ValidateValueIsNotNullOrEmpty : ICalculatorValidationRule
{
    public bool IsValid(string value)
    {
        return !String.IsNullOrEmpty(value);
    }

    public string ErrorMessage
    {
        get
        {
            return &quot;Please enter a number&quot;;
        }
    }
}

[Export(typeof(ICalculatorValidationRule))]
public class ValidateValueIsANumber : ICalculatorValidationRule
{
    public bool IsValid(string value)
    {
        if (!String.IsNullOrEmpty(value))
        {
            int number;
            return int.TryParse(value, out number);
        }
        return true;
    }

    public string ErrorMessage
    {
        get { return &quot;That's not a number&quot;; }
    }
}

[Export(typeof(ICalculatorValidationRule))]
public class ValidateValueIsNotNegative : ICalculatorValidationRule
{
    public bool IsValid(string value)
    {
        int number;
        if (int.TryParse(value, out number) &amp;&amp; number  &lt; 0)
        {
            return false;
        }
        return true;
    }

    public string ErrorMessage
    {
        get { return &quot;Number cannot be negative&quot;; }
    }
}

[Export(typeof(ICalculatorValidationRule))]
public class ValidateValueIsLessThanHundred : ICalculatorValidationRule
{
    public bool IsValid(string value)
    {
        int number;
        if (int.TryParse(value, out number) &amp;&amp; number &gt; 100)
        {
            return false;
        }
        return true;
    }

    public string ErrorMessage
    {
        get { return &quot;That number is too big!&quot;; }
    }
}
</pre><p>An alternative to parsing the value to an integer in the validation rules to check the range would be to order how MEF composes the validation rules and ensure rule to validate the value is an integer is done earlier.</p><p>More information about this can be found in answer to this question on Stack Overflow &#8211; <a
href="http://stackoverflow.com/questions/1770297/how-does-mef-determine-the-order-of-its-imports/1772554">How does MEF determine the order of its imports?</a></p><h3 class="subheading">ImportMany example in MEF</h3><p>By using the ImportMany attribute on a collection in MEF we can iterate over all of the parts which export the ICalculatorValidatorInterface and check the value passes the validation rule by calling the IsValid method.</p><p>If the value is not valid a exception is thrown with the relevant error message.</p><p>The code below shows how the CalculatorValidator class would look</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public class CalculatorValidator
{
    [ImportMany]
    public IEnumerable&lt;ICalculatorValidationRule&gt; CalculatorValidationRules { get; set; }

    public void ValidateNumber(string value)
    {
        foreach (var calculatorValidationRule in CalculatorValidationRules)
        {
            if (!calculatorValidationRule.IsValid(value))
            {
                throw new Exception(calculatorValidationRule.ErrorMessage);

            }
        }
    }
}
</pre><h3 class="subheading">Couldn&#8217;t have done it without the extensibility of MEF</h3><p>If we wanted to add a new validation rule, all we have to do is create another class which implements the ICalculatorValidationRule interface, add an export attribute and MEF will do the rest.</p><blockquote><p>The CalculatorValidator class is now open to extension but closed for modification</p></blockquote> ]]></content:encoded> <wfw:commentRss>http://www.arrangeactassert.com/applying-the-open-closed-principle-in-silverlight-and-wpf-using-mef/feed/</wfw:commentRss> <slash:comments>4</slash:comments> </item> <item><title>SOLID design principles using MEF in Silverlight and WPF</title><link>http://www.arrangeactassert.com/solid-design-principles-using-mef-in-silverlight-and-wpf/</link> <comments>http://www.arrangeactassert.com/solid-design-principles-using-mef-in-silverlight-and-wpf/#comments</comments> <pubDate>Thu, 17 Jun 2010 21:14:01 +0000</pubDate> <dc:creator>Jag Reehal</dc:creator> <category><![CDATA[MEF]]></category> <category><![CDATA[Silverlight]]></category> <category><![CDATA[WPF]]></category><guid
isPermaLink="false">http://www.arrangeactassert.com/?p=851</guid> <description><![CDATA[In this part of the Silverlight refactoring series we will be looking at two ways the Managed Extensibility Framework (MEF) can help you refactor Silverlight or WPF applications to follow SOLID design principles. The code used in this post can be downloaded here. Apart from saying through discovery and composition MEF gives you the ability [...]]]></description> <content:encoded><![CDATA[<p>In this part of the <a
href="http://www.arrangeactassert.com/how-to-refactor-and-build-better-microsoft-silverlight-applications/">Silverlight refactoring series</a> we will be looking at two ways the <a
href="http://mef.codeplex.com/">Managed Extensibility Framework (MEF)</a> can help you refactor Silverlight or WPF applications to follow <a
href="http://en.wikipedia.org/wiki/Solid_(object-oriented_design)">SOLID design principles</a>.</p><p>The code used in this post can be downloaded <a
ref="nofollow" href="http://cid-8a29bf85dc9538dc.office.live.com/self.aspx/.Public/Silverlight%20Demos/SilverlightCalculator/SilverlightCalculatorMEF.zip">here</a>.</p><p>Apart from saying</p><blockquote><p>through discovery and composition MEF gives you the ability to build applications which will be flexible enough for your every need</p></blockquote><p>I won’t be covering what MEF is or how it works in depth in this post.  Instead I recommend checking out the following blogs as well as the <a
href="http://mef.codeplex.com/">MEF site on Codeplex</a> for some great tutorials.</p><ul><li><a
href="http://mtaulty.com/CommunityServer/blogs/mike_taultys_blog/default.aspx">Mike Taulty&#8217;s Blog</a></li><li><a
href="http://blogs.msdn.com/b/gblock/">Glenn Block&#8217;s Blog</a></li></ul><h3 class="subheading">What problem does MEF solve in this application?</h3><p>The code below shows the Calculate method in the ViewModel.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public void  Calculate()
{
    Calculator calculator = new Calculator();
    Result = calculator.Add(Convert.ToInt32(FirstValue), Convert.ToInt32(SecondValue)).ToString();
}
</pre><p>Notice how Calculator class is created and used within the method.  This means there&#8217;s no way of changing what class is used for calculations without modifying the code in the ViewModel.</p><p>In other words <strong>the calculator is tightly coupled to the ViewModel</strong>.</p><h3 class="subheading">Composing, Initializing, Setting up, Bootstrapping, Configuring or whatever you want to call it in MEF</h3><p>MEF works by using a catalog to discover extensions within assemblies.  As the assemblies used in this application are in same XAP we can call the CompositionInitializer SatisfyImports method to automatically configure a container and compose the parts within it.</p><p>Looking at the class diagram for the application</p><p><img
src="http://www.arrangeactassert.com/wp-content/themes/resources/images/SilverlightMVVMViewModelSRP.png" alt="Silverlight Class Diagram" /></p><p>we could decide</p><ul><li>only the Calculator class will be an composable part</li><li>the ViewModel and the Calculator will be composable parts</li><li>the CalculatorPage, ViewModel and the class should all be composable parts</li></ul><p>As this application only contains a single page we will go with the second option.  This means we will be calling the CompositionInitializer SatisfyImport method in the CalculatorPage constructor as shown below</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public CalculatorPage()
{
    InitializeComponent();
    CompositionInitializer.SatisfyImports(this);
}
</pre><h3 class="subheading">Adding MEF Export Attributes</h3><p>An export attribute is used to make classes and properties discoverable to the catalog and composable by the container.</p><p>As the Calculator class is used by the ViewModel we need to add an Export attribute to it. Because the Calculator implements the ICalculator interface we can use this as the <a
href="http://mef.codeplex.com/wikipage?title=Parts&#038;ANCHOR">contract type</a>.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
[Export(typeof(ICalculator))]
public class Calculator : ICalculator
{
public int Add(int firstValue, int secondValue)
{
    return firstValue + secondValue;
}
}
</pre><p>Similarly as the ViewModel is used by the CalculatorPage it also needs to be decorated with an Export attribute.  As no contract is specified, MEF will use the fully qualified name of the type as the contract.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
[Export]
public class CalculatorViewModel : INotifyPropertyChanged
{
    .....
}
</pre><p>An important thing to remember is that the export attribute is not allowed on the instance passed to SatisfyImports otherwise you will see the error below</p><p><img
src="http://www.arrangeactassert.com/wp-content/themes/resources/images/MEFExportError.png" alt="MEF Export Error" /></p><h3 class="subheading">Using MEF Property Imports</h3><p>To use property imports in MEF we need to add a Calculator property to the ViewModel add decorate it with an Import attribute.  In Silverlight MEF requires the property to be public.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
[Import]
public ICalculator Calculator { get; set; }
</pre><p>The Calculate method in the ViewModel uses the property like this</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public void Calculate()
{
    Result = Calculator.Add(Convert.ToInt32(FirstValue), Convert.ToInt32(SecondValue)).ToString();
}
</pre><p>In the code behind of the CalculatorPage we need to add a CalculatorViewModel property, decorate it with an Import attribute and set it as the data context.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public partial class CalculatorPage : UserControl
{
    [Import]
    public CalculatorViewModel CalculatorViewModel { get; set; }

    public CalculatorPage()
    {
        InitializeComponent();
        CompositionInitializer.SatisfyImports(this);
        DataContext = CalculatorViewModel;
    }
}
</pre><p>If we run the application as it is MEF composes all the parts of the application and we are able to add numbers together&#8230; which is good but not great because I don’t recommend you should build applications only using property imports.</p><h3 class="subheading">Using MEF Constructor Imports</h3><p>I always try to follow the SOLID design principles whenever I’m developing applications.</p><p>The D in SOLID design principles stands for <a
href="http://en.wikipedia.org/wiki/Dependency_inversion_principle">Dependency Inversion Principle</a>.</p><p>One of the first things you should be taught when learning test driven development or even good coding practices is how SOLID design principles will help you create applications that are easier to develop, configure, maintain and unit test.</p><p>See my blog post &#8216;<a
href="http://www.arrangeactassert.com/how-to-write-better-unit-tests-using-rhinomocks-and-stubs/">How to write better unit tests using RhinoMocks and stubs</a>&#8216; for an example.</p><p>The good news is MEF supports constructor imports.</p><p>Using the ImportingConstructor attribute the CalculatorViewModel now takes in a Calculator in its constructor as shown below</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
[ImportingConstructor]
public CalculatorViewModel(ICalculator calculator)
{
    _calculator = calculator;
    ...
}
</pre><p>and the calculate method uses the calculator like this</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public void Calculate()
{
    Result = _calculator.Add(Convert.ToInt32(FirstValue), Convert.ToInt32(SecondValue)).ToString();
}
</pre><h3 class="subheading">Take care not to over engineer</h3><p>So what about the importing the ViewModel in the CalculatorPage?  We could stick to using a property for the ViewModel or pass it in the ViewModel constructor (in which case the call to CompositionInitializer SatisfyImports method will have to done in the App.xaml code behind).</p><p>I would be inclined to leave it as it is.  Because we want to be able to unit test the ViewModel it makes sense to use importing constructors so we stub out the calculator.</p><p>Are we ever going to unit test the CalculatorPage?  Probably not, and if we do need to, it’s not a major refactoring task.</p><p>In any case thanks to MEF the ViewModel can be changed without modifying the code behind for the CalculatorPage.</p><h3 class="subheading">So what have we achieved?</h3><p>By using SOLID design principles and MEF we have managed to remove the tight coupling between the ViewModel and the Calculator.</p><p>There is a lot of discussion about what MEF is in the development community.  Despite numerous claims and comments that it&#8217;s not a dependency injection framework, I can&#8217;t help thinking it takes a step closer to being one with each release.</p><p>The last thing I&#8217;ll say about MEF is that</p><blockquote><p>the number of options you have of using MEF is either impressive or confusing depending on what side of the fence you sit on</p></blockquote><p>If you have arrived here from a search engine, this post is part of series about <a
href="http://www.arrangeactassert.com/how-to-refactor-and-build-better-microsoft-silverlight-applications/">refactoring Silverlight applications</a>.</p><p>So if you’re thinking, what if there&#8217;s an exception converting a string into an integer, check out the post &#8216;<a
href="http://www.arrangeactassert.com/validation-in-silverlight-and-wpf-using-validatesonexceptions/">Validation in Silverlight and WPF using ValidatesOnExceptions</a>&#8216; which shows one approach in solving this problem using exceptions.</p> ]]></content:encoded> <wfw:commentRss>http://www.arrangeactassert.com/solid-design-principles-using-mef-in-silverlight-and-wpf/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>How to Apply the Single Responsibility Principle to View Models in Silverlight and WPF</title><link>http://www.arrangeactassert.com/how-to-apply-the-single-responsibility-principle-to-view-models-in-silverlight-and-wpf/</link> <comments>http://www.arrangeactassert.com/how-to-apply-the-single-responsibility-principle-to-view-models-in-silverlight-and-wpf/#comments</comments> <pubDate>Mon, 14 Jun 2010 21:46:41 +0000</pubDate> <dc:creator>Jag Reehal</dc:creator> <category><![CDATA[MVVM]]></category> <category><![CDATA[Silverlight]]></category> <category><![CDATA[Unit tests]]></category> <category><![CDATA[WPF]]></category><guid
isPermaLink="false">http://www.arrangeactassert.com/?p=828</guid> <description><![CDATA[When you&#8217;re using the MVVM pattern with WPF or Silverlight it&#8217;s very easy to a have ViewModels that do too much. In this part of the Silverlight Refactoring series we will convert a ViewModel with multiple responsibilities so that it adheres to the Single Responsibility Principle (SRP). The code used in this post can be [...]]]></description> <content:encoded><![CDATA[<p>When you&#8217;re using the MVVM pattern with WPF or Silverlight it&#8217;s very easy to a have ViewModels that do too much.</p><p>In this part of the Silverlight Refactoring series we will convert a ViewModel with multiple responsibilities so that it adheres to the <a
href="http://en.wikipedia.org/wiki/Single_responsibility_principle">Single Responsibility Principle (SRP)</a>.</p><p>The code used in this post can be downloaded <a
href="http://cid-8a29bf85dc9538dc.office.live.com/self.aspx/.Public/Silverlight%20Demos/SilverlightCalculator/SilverlightCalculatorSingleResponsibilityPrinciple.zip">here</a>.</p><h3 class="subheading">Why should you care?</h3><p>Currently the ViewModel looks like this</p><pre class="brush: csharp; gutter: false; highlight: [22,23,24,25]; title: ; toolbar: true; notranslate">
using System;
using System.ComponentModel;
using System.Windows.Input;

namespace SilverlightCalculator
{
    public class CalculatorViewModel : INotifyPropertyChanged
    {
        private string _firstValue;
        private string _secondValue;
        private string _result;

        private readonly ICommand _calculateCommand;       

        public event PropertyChangedEventHandler PropertyChanged;

        public CalculatorViewModel()
        {
            _calculateCommand = new RelayCommand(Calculate){IsEnabled = true};
        }

        public void Calculate()
        {
            Result = (Convert.ToInt32(FirstValue) + Convert.ToInt32(SecondValue)).ToString();
        }

        public string FirstValue
        {
            get { return _firstValue; }
            set
            {
                _firstValue = value;
                OnPropertyChanged(&quot;FirstValue&quot;);
            }
        }

        public string SecondValue
        {
            get { return _secondValue; }
            set
            {
                _secondValue = value;
                OnPropertyChanged(&quot;SecondValue&quot;);
            }
        }

        public string Result
        {
            get { return _result; }
            private set
            {
                _result = value;
                OnPropertyChanged(&quot;Result&quot;);
            }
        }

        public ICommand CalculateCommand
        {
            get { return _calculateCommand; }
        }

        protected void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this,
                    new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}
</pre><p>As you can see the logic to add two numbers is in the Calculate method of the ViewModel.</p><p>Therefore <strong>the ViewModel is responsible for calculating two numbers</strong>.</p><p>A ViewModel without separation of concerns is difficult to test, maintain and contains code you can&#8217;t reuse.</p><p>Although we&#8217;re only adding two numbers here, brushing the issue under the carpet will have consequences later down the line.</p><p>For example in addition to adding numbers what if another developer was given the task of storing the result in a database.</p><p>If the ViewModel was as it is now, with no <a
href="http://en.wikipedia.org/wiki/Separation_of_concerns">separation of concerns</a>, there is a chance they would put the code to store the value in the calculate method like this</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public void Calculate()
{
    // Calculate result
    Result = (Convert.ToInt32(FirstValue) + Convert.ToInt32(SecondValue)).ToString();

    // Store value in database
    DatabaseConnection connection = new DatabaseConnection();
    DatabaseCommand command = new DatabaseCommand(&quot;TSQL TO STORE RESULT&quot;, connection);
    command.ExecuteNonQuery();
}
</pre><p>Now the ViewModel would be responsible for two things.  Next it would be three and this would continue until someone decides to separate the concerns or it gets to a stage where it&#8217;s impossible to work with let alone read.</p><h3 class="subheading">Refactoring the ViewModel to follow the single responsibility principle</h3><p>Let’s start by creating a class for calculating numbers.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public class Calculator
{
    public int Add(int firstValue, int secondValue)
    {
        return firstValue + secondValue;
    }
}
</pre><p>Notice how the parameters passed to the method are integers, the calculator doesn&#8217;t accept string values.</p><p>What we are saying here is while it&#8217;s acceptable for the ViewModel to use strings for storing numbers the domain layer (or business logic if you prefer) does not.</p><p>In other words the add method does nothing more than add two numbers together.  Validation should be handled elsewhere.</p><p>This makes the unit tests for the calculator very easy to write</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
[TestFixture]
public class When_calculating_numbers
{
    [Test]
    public void Should_be_able_to_add_two_numbers_together()
    {
        // Arrange
        Calculator calculator = new Calculator(); 

        // Act
        var result = calculator.Add(5, 5);

        //Assert
        Assert.That(result, Is.EqualTo(10));
    }
}
</pre><p>The code below shows how the ViewModel <strong>could</strong> create an instance of the Calculator class and call the Add Method.  Notice how I say could and not should.  We&#8217;ll see why later in the series.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public void Calculate()
{
    Calculator calculator = new Calculator();
    Result = calculator.Add(Convert.ToInt32(FirstValue), Convert.ToInt32(SecondValue)).ToString();
}
</pre><h3 class="subheading">So what have we achieved?</h3><p>As <a
href="http://programmer.97things.oreilly.com/wiki/index.php/The_Boy_Scout_Rule">good boy scouts</a> we have ‘left the ViewModel cleaner than we found it’.</p><p>By following the single responsibility principle we have created a ViewModel which is a better canvas for other developers to work with.</p><p>If you have arrived here from a search engine, this post is part of series about refactoring Silverlight applications.  So if you’re thinking why is the calculator class tightly coupled to the ViewModel?  Find out how this can be resolved by <a
href="http://www.arrangeactassert.com/solid-design-principles-using-mef-in-silverlight-and-wpf/"> applying SOLID design principles using MEF in Silverlight and WPF</a>.</p> ]]></content:encoded> <wfw:commentRss>http://www.arrangeactassert.com/how-to-apply-the-single-responsibility-principle-to-view-models-in-silverlight-and-wpf/feed/</wfw:commentRss> <slash:comments>2</slash:comments> </item> </channel> </rss>
<!-- Served from: www.arrangeactassert.com @ 2012-02-06 00:11:12 by W3 Total Cache -->
