<?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>xaml ninja &#187; MVVM</title>
	<atom:link href="http://blogs.xamlninja.com/tag/mvvm/feed" rel="self" type="application/rss+xml" />
	<link>http://blogs.xamlninja.com</link>
	<description>xaml ninja moves</description>
	<lastBuildDate>Tue, 10 Jan 2012 19:46:49 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>WP7 Contrib &#8211; Bing Service Wrapper Part I &#8211; Location</title>
		<link>http://blogs.xamlninja.com/xaml/wp7-contrib-bing-service-wrapper-part-i-location</link>
		<comments>http://blogs.xamlninja.com/xaml/wp7-contrib-bing-service-wrapper-part-i-location#comments</comments>
		<pubDate>Fri, 24 Jun 2011 14:31:13 +0000</pubDate>
		<dc:creator>rich</dc:creator>
				<category><![CDATA[Bing Services]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[WP7]]></category>
		<category><![CDATA[WP7Contrib]]></category>
		<category><![CDATA[Xaml]]></category>
		<category><![CDATA[WP7Dev]]></category>

		<guid isPermaLink="false">http://blogs.xamlninja.com/?p=499</guid>
		<description><![CDATA[This being the first post about the Wrappers I thought that we should break the ice with the most commonly used service. Location. Out of all of the services this is the simplest to call but also we would suspect the most widely used. When you combine this service with the device location based WP7C [...]]]></description>
			<content:encoded><![CDATA[<p>This being the first post about the Wrappers I thought that we should break the ice with the most commonly used service. Location. Out of all of the services this is the simplest to call but also we would suspect the most widely used. When you combine this service with the device location based WP7C bits then you can build your geo location aware app and have it plotting to a map and moving in real-time, or you could be helping your user to find the location of an address.</p>
<p>In the sample for using the location service we tackle both of these scenarios.</p>
<p>So, I am going to jump straight in here and assume that you have either looked at the sample in the Spikes folder of the <a href="http://wp7contrib.codeplex.com/" target="_blank">WP7 Contrib</a> (WP7C) or you have some experience of using the Rest API provided by the Bing Maps endpoint. If you have not done this then I would suggest opening up the sample and taking a quick look at the Location View Model, its pretty straight forwards so you should be back in 10.</p>
<p>First off if you have not already created a project then you need too. If you are using MVVM and some sort of DI library cool, if not no worries. There are two different options provided by the Location Service from the Bing REST API; you can either use the Geo Coordinate Location of the device and pass this to the service in order to give you back a current address; or you can enter a location to find out what Geo Coordinate Location is.</p>
<p>If you are not already using the WP7C components in you app (shame on you J) then you need to add a couple of references in order to get this up and running, these include:-</p>
<ul>
<li>WP7Contrib.Services
<ul>
<li>BingMaps</li>
<li>BingMaps.Model</li>
<li>Location</li>
</ul>
</li>
</ul>
<p>These are the basic bits that you need to get your geo location app up and running. Once we have included those assemblies then we need to define the interfaces we want to use and the data objects that correspond to the location service calls.</p>
<p>First up we need to declare the private fields so let’s go ahead and do that</p>
<pre class="brush: csharp">
private readonly IBingMapService bingMapService;
private readonly ILocationService locationService;
private LocationRect boundingRectangle;
private GeoCoordinate currentDeviceGeoCoordinate;
private IDisposable currentLocationObserver;
private RelayCommand selectFindMyCurrentLocationCommand;
private RelayCommand selectFindGeoLocationFromAddressCommand;
private Address address;
private LocationData locationDataByPoint;
</pre>
<p>&nbsp;</p>
<p>Next, we need to create a constructor for our VM. You will notice that not only am I using the ILocationService which is the WP7C’s Rx location component but we are also going to pass in a IBingMapService which is our wrapper that we will use to call the REST services. The other interfaces that I am using here are the navigation service and the logging component from WP7C.</p>
<pre class="brush: csharp">
public LocationViewModel(
INavigationService navigationService,
ILocationService locationService,
IBingMapService bingMapService,
ILog log)
: base(navigationService, log)
{
this.locationService = locationService;
this.bingMapService = bingMapService;
this.address = new Address {CountryRegion = &quot;UK&quot;, PostalCode = &quot;LE17 5ER&quot;};
}
</pre>
<p>&nbsp;</p>
<p>Currently, and this is consistent across all of our samples we are using Funq as our DI framework of choice, its light and simple which is why it’s great for WP7, we are not bound to Funq in anyway so if you want to use your Favourite DI then you can do so.</p>
<p>With our constructor defined we need to go ahead and do our register and resolve in the bootstrapper.</p>
<p>There is quite a bit of stuff happening in the bootstrapper, mainly because of the fact that we are taking advantage of the different components inside of the WP7C, now you don’t have to use these however if you need things like logging; want to store data; and if you have a design where you are not loading all the VM’s upfront take a look at the Last Message Replay. As this is the first in a series of posts we can deconstruct what is happening here in the future articles I will only reference this section.</p>
<p>The code below setups the Logging bits for us.</p>
<pre class="brush: csharp">
this.Container.Register&lt;ILogManager&gt;(c =&gt; new LoggingService(&quot;BingMaps&quot;));
this.Container.Register&lt;ILog&gt;(c =&gt; this.Container.Resolve&lt;ILogManager&gt;());
&lt;p&gt;var logManager = this.Container.Resolve&lt;ILogManager&gt;();
logManager.Enable();
</pre>
<p>&nbsp;</p>
<p>Here we setup the settings for the app and assign the key that we want to use for bing maps. The registered key in the code is registered to the WP7C so I would advise that you register, it does not take long and the key is generated instantly.</p>
<pre class="brush: csharp">
this.Container.Register&lt;IStoreSettings&gt;(c =&gt; new SettingsStore(this.Container.Resolve&lt;ILog&gt;()));
this.Container.Register&lt;ISettings&gt;(c =&gt; new Settings(&quot;Bing Key&quot;));
var serialisationAssemblies = new List&lt;Assembly&gt; { this.GetType().Assembly };
</pre>
<p>&nbsp;</p>
<p>Setup the cache provider and initialise it.</p>
<pre class="brush: csharp">
this.Container.Register&lt;ICacheProvider&gt;(c =&gt; new  IsolatedStorageCacheProvider(&quot;BingMaps&quot;, serialisationAssemblies,  c.Resolve&lt;ILog&gt;()));
var cache = this.Container.Resolve&lt;ICacheProvider&gt;();
System.Threading.ThreadPool.QueueUserWorkItem(state =&gt; cache.PreemptiveInitialise());
</pre>
<p>&nbsp;</p>
<p>Setup the last replay messenger.</p>
<pre class="brush: csharp">
this.Container.Register&lt;IMessenger&gt;(c =&gt; new LastMessageReplayMessenger());
</pre>
<p>&nbsp;</p>
<p>Setup the WP7C Navigation Service.</p>
<pre class="brush: csharp">
this.Container.Register&lt;INavigationService&gt;(

c =&gt; new ApplicationFrameNavigationService(((App)Application.Current).RootFrame));
</pre>
<p>&nbsp;</p>
<p>Setup the WP7C Network service</p>
<pre class="brush: csharp">
this.Container.Register&lt;INetworkService&gt;(c =&gt; new NetworkMonitor(5000));
</pre>
<p>&nbsp;</p>
<p>Setup the WP7C Storage service.</p>
<pre class="brush: csharp">
var assemblies = new List&lt;Assembly&gt; { this.GetType().Assembly, typeof(BaseModel).Assembly };
this.Container.Register&lt;IStorageService&gt;(c =&gt; new StorageService(assemblies, c.Resolve&lt;ILog&gt;()));
</pre>
<p>&nbsp;</p>
<p>As we are using the Resource Client from WP7C we also need to add this setup code into our bootstrapper.</p>
<pre class="brush: csharp">
this.Container.Register&lt;IEncodeProperties&gt;(c =&gt; new UrlEncoder());
this.Container.Register&lt;IHandleResourcesFactory&gt;(c =&gt; new ResourceClientFactory(c.Resolve&lt;ILog&gt;()));
</pre>
<p>&nbsp;</p>
<p>The final part is that we need to wire in the IBingMapService which needs to be resolved using some of the interfaces that we registered earlier.</p>
<pre class="brush: csharp">
this.Container.Register&lt;IBingMapService&gt;(c =&gt; new BingMapService(
c.Resolve&lt;IHandleResourcesFactory&gt;(),
c.Resolve&lt;IEncodeProperties&gt;(),
c.Resolve&lt;ICacheProvider&gt;(),
c.Resolve&lt;ISettings&gt;(),
c.Resolve&lt;ILog&gt;()));
</pre>
<p>&nbsp;</p>
<p>Ok, so we nearly have, all of the underlying plumbing done what we need to do next is to setup the VM locator. If you need more details on this please refer to the sample code. Once you have the VM locator updated we can go ahead and bind our Data Context up to the VM using the service locator pattern in Xaml.</p>
<p>As I mentioned at the start of this article, the UI’s are more about form and function, so our intentions are purely to visualise all the different types of data coming back from the service. So, for this we went with simple UI controls to make sure that the data being returned from our request is correct.</p>
<p>Now, that we have the plumbing in place, and some simple UI that displays the responses, our next step is to make our requests out to the Bing Services. This code is going to live in the VM.</p>
<p>The first thing on our list to implement is that we need to make our app location aware, everything you need to do this is already baked in the WP7C, it just requires a simple bit of Rx to get it wired in. In order to do this we need to leverage the ILocation Service that we injected into the VM as this will find out what our current location is.</p>
<pre class="brush: csharp">
private GeoCoordinate currentDeviceGeoCoordinate;
private IDisposable currentLocationObserver;
private void ExecuteSelectFindMyCurrentLocationCommand()
{
try
{
this.currentLocationObserver =
this.locationService.Location()
.ObserveOnDispatcher()
.Subscribe(geoCoordinate =&gt;
{
this.CurrentDeviceGeoCoordinate = geoCoordinate;
this.SearchForLocation(this.BuildLocationSearchForPoint());
});
}
catch (Exception exn)
{
MessageBox.Show(string.Format(&quot;Failed! Message - &#039;{0}&quot;, exn.Message), &quot;Location Search&quot;,                MessageBoxButton.OK);
}}
</pre>
<p>&nbsp;</p>
<p>Notice in the subscribe how we are assigning a value to the VM’s Current Device Geo Coordinate Property which is bound up in the view; also note that we are then doing a Search for a geo location and passing into this method the result from the Build Location Search For Point. We decided that in order for us to wrap up all the services and provide a common API from which users can use the services we would adopt a factory style pattern. So, what’s going on in the Build method? Well here we are calling out to the factory and asking it to create what we need in order to query the Bing services for dealing with the request.</p>
<pre class="brush: csharp">
private ILocationSearchPointCriterion BuildLocationSearchForPoint()
{
return CriterionFactory.CreateLocationSearchForPoint(this.CurrentDeviceGeoCoordinate);
}
</pre>
<p>&nbsp;</p>
<p>And that is all you need to add location awareness to your app, I hope that you agree with me that this is rather straight forwards. Next up we need to build out the search for location method, which is going to use the Bing wrapper service from the WP7C to search for a location. If you have looked over the code you will see that we have 2 overloaded methods, one which deals with Geo Location and the other which deals with addresses.</p>
<pre class="brush: csharp">
private void SearchForLocation(ILocationSearchPointCriterion criterion)
{
this.bingMapService.SearchForLocationUsingPoint(criterion)
.ObserveOnDispatcher()
.Subscribe(this.ProcessSearchLocationByPointResponse,
FailedSearch,
CompletedSearch);
}
</pre>
<p>&nbsp;</p>
<p>And for completeness I have included the code for the address mechanism below.</p>
<p>&nbsp;</p>
<pre class="brush: csharp">
private void SearchForLocation(ILocationSearchAddressCriterion criterion)
{
this.bingMapService.SearchForLocationUsingAddress(criterion)
.ObserveOnDispatcher()
.Subscribe(this.ProcessSearchLocationByAddressResponse,
FailedSearch,
CompletedSearch);
}
</pre>
<p>&nbsp;</p>
<p>Note that there are a couple of differences between the overloads; first the interface type that we are passing into our method for locations we always need to use the ILocationSearchPointCriterion and for addresses we need to use the ILocationSearchAddressCriterion; and the other difference is that we use a different method to deal with the response that we get sent from the Bing Services.</p>
<pre class="brush: csharp">
private void ProcessSearchLocationByPointResponse(LocationSearchResult result)
{
if (result == null)
{
return;
}
if (result.Locations.Count != 0)
this.LocationDataByPoint = result.Locations[0];
}
</pre>
<p>In order to successfully process the data and then work on this data the WP7C provides you with the data transformation classes that you need and does all the map and wrap code so that you don’t have to. In the code above this is illustrated by our use of the LocationDataByPoint property which uses the Location Data class from the WP7C, we are using databinding in the view and wiring up to this property from the VM .</p>
<p>So, just to recap what we have covered are a couple of things here; first we made our app Geo Location aware by using the WP7C Rx location service; which was then wired up to the Bing Services Wrapper and we used this to provide an address of the device&#8217;s current location; and for completeness we provide a way for the user to enter details of an address and the app responds with a Geo Location that corresponds to the address.</p>
<p>Admittedly we are doing some simple tasks here however its super important that we put in the ground work so that you can gain a deep understanding of how the wrappers work. We would really like to hear your feedback, if you have built an app using the Bing services we would also be interested in talking to you about your sceanrios.</p>
<p>In the next post I will dig into using the Route Service.</p>
<p><a href="http://awkwardcoder.blogspot.com/" target="_blank">Ollie</a> has some deep dive blog posts planned which are based around the patterns that he is using along with some gems of information around using Rx with these more traditional patterns so watch out for those.</p>
<p>Enjoy!</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.xamlninja.com/xaml/wp7-contrib-bing-service-wrapper-part-i-location/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>uk tech.days 2011</title>
		<link>http://blogs.xamlninja.com/silverlight/uk-tech-days-2011</link>
		<comments>http://blogs.xamlninja.com/silverlight/uk-tech-days-2011#comments</comments>
		<pubDate>Mon, 23 May 2011 12:31:12 +0000</pubDate>
		<dc:creator>rich</dc:creator>
				<category><![CDATA[Blend]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[Presentations]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[uktechdays]]></category>
		<category><![CDATA[Xaml]]></category>

		<guid isPermaLink="false">http://blogs.xamlninja.com/?p=464</guid>
		<description><![CDATA[This week Ollie and I will presenting at the UK tech.days happening in the Fulham, London. Our first session will be all about building Data Data Intensive apps for WP7 and we are really looking forward to talking to you about what we have learnt building these types of applications. We are also going to [...]]]></description>
			<content:encoded><![CDATA[<p>This week <a href="http://awkwardcoder.blogspot.com/" target="_blank">Ollie </a>and I will presenting at the UK <a href="http://uktechdays.cloudapp.net/home.aspx">tech.days</a> happening in the Fulham, London.</p>
<p>Our first session will be all about building <a href="http://uktechdays.cloudapp.net/techdays-live/windows-phone-1-state-of-the-nation.aspx" target="_blank">Data Data Intensive apps for WP7</a> and we are really looking forward to talking to you about what we have learnt building these types of applications. We are also going to show off bits from the WP7 Contrib that help to make building these types of applications easier. It&#8217;s going to be a demo packed session so hold on for a rollercoaster ride. We are making avaliable all our demos before the session so if you are attending and interested you can download these from the skydrive link at the bottom of the post.</p>
<p>My other session obviously will be about using Blend =P  and the title of the session is aptly named <a href="http://uktechdays.cloudapp.net/techdays-live/building-rich-client-applications.aspx">&#8220;Expression Blend for Silverlight Developers&#8221;</a>.</p>
<p>The session is broken down into 3 sub sections; designer developer collaboration; Blend quick fire tips; and the main part, building out an app from a Adobe Photoshop/Illustrator visual design into a functional Silverlight app. This session is aimed particularly at developers who are just starting out with Blend, however even if you have been using Blend for a while there should be plenty of refreshers.</p>
<p>Now, I had thought about doing</p>
<p><em> “… this is how I create a button in Blend, and oh look I can make it into a circle and bounce across the screen…”</em></p>
<p>as much as I love attending these sessions and love the buzz afterwards sometimes it can be difficult to relate the content to a problem you may currently be working on.</p>
<p>Up on skydrive you will find; the .psd file I am going to use; an unstyled version; and a completed version that is styled. There is still plenty more to do so the scope is open and hopefully you will be able to use this as a reference point for future apps that you build. Therefore, I thought that it would be an interesting idea to see how attendees if they so wished can use the session as a hands-on Blend training hour, and if you want to participate then you can. Otherwise you can sit back and watch how we build a static vector graphic into a functioning app.</p>
<p>If you are planning on attending and would like me to cover off anything in particular I will do my best to make it happen, otherwise I would be more than happy to chat during the event, if you can bring code or have a scenario that would really help me understand the context of your questions.</p>
<p>You can find all of the goodies up on the sky drive folder.</p>
<p>See you there!</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.xamlninja.com/silverlight/uk-tech-days-2011/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>WP7 Contrib &#8211; When messaging becomes messy and services shine</title>
		<link>http://blogs.xamlninja.com/mvvm/wp7-contrib-when-messaging-becomes-messy-and-services-shine</link>
		<comments>http://blogs.xamlninja.com/mvvm/wp7-contrib-when-messaging-becomes-messy-and-services-shine#comments</comments>
		<pubDate>Tue, 08 Feb 2011 16:58:58 +0000</pubDate>
		<dc:creator>rich</dc:creator>
				<category><![CDATA[MVVM]]></category>
		<category><![CDATA[WP7]]></category>
		<category><![CDATA[WP7Contrib]]></category>
		<category><![CDATA[Xaml]]></category>

		<guid isPermaLink="false">http://blogs.xamlninja.com/?p=358</guid>
		<description><![CDATA[In a previous post I introduced you to the Last Message Replay Messenger, in this post I wanted to dig into something that happened recently where I needed to provided the ability in the application for the user to add an item to a favourites list. Ok so fairly straight forwards, however there was a [...]]]></description>
			<content:encoded><![CDATA[<p>In a previous <a href="http://blogs.xamlninja.com/xaml/wp7-contrib-the-last-messenger" target="_blank">post </a>I introduced you to the Last Message Replay Messenger, in this post I wanted to dig into something that happened recently where I needed to provided the ability in the application for the user to add an item to a favourites list. Ok so fairly straight forwards, however there was a slight twist. Not only can the user add items to their favourites from a list but they can also add an item to their favourites list from a number  of different places in the application.  Each view has a different VM and we don’t want to chain the VM&#8217;s together as then they know about each other; we also don’t want to use the VM Locator from the Xaml and call the same relay command to perform the action; so on the surface this looks like a job for a messenger :-</p>
<ol>
<li>Define the Message which wraps up the data</li>
<li>Add the IMessenger interface as a parameter in the VM constructor</li>
<li>Register the IMessenger interface with the Last Message Replay Messenger</li>
<li>In the originator register the type of message data your interested in with the Notification Message Action</li>
<li>In the VM which is interested in the message register for the Message defined in step 1</li>
<li>Provide a method that deals with the received messages and sets up the data context of the View</li>
</ol>
<p>Now this works just fine when I want to pass data to disconnected lazy loading VM&#8217;s but I got into trouble when it came to stashing this content. The main reason is that it comes down to a level of responsibility which results in the question of who owns the data ? and who is responsible for storing the data ?</p>
<p>What I ended up with was a collection of favourites that were being managed by each VM that required their Views to have the ability; add to the favourites list and then fire a message broadcasting that here is the new favourite item which needs to be added into the favourites collection. Cool!</p>
<p>So all is cool now? Well sure until it comes to building out the persistence mechanism using the override Activate and DeActive methods that the VM Base provides us with in order to store the data. My next move was then to start changing the data inside of the Message to a collection of the same type, but this solution means that I now pass around a reference pointer to the collection in the message and each VM is then responsible for adding new items. The Favourites VM is then inherently responsible for persisting the collection. Ok so that gets us closer. Unfortunately, the Favourites Page and VM are not primaries in the user journey through the app therefore, there is a high potential that the user will not have viewed the Favourites Page resulting the Favourites VM not being instantiated and now things start to get sticky again….</p>
<p>At this point its time for a brew&#8230;. I could continue trying to bend the message pattern to fit our needs but its generating a large amount of friction when we try and push. This is where using a service makes far more sense. Now, if you chat to <a href="http://awkwardcoder.blogspot.com/" target="_blank">Ollie </a>he will say well this is all about &#8220;ask don’t tell, Rich&#8221;.  Therefore, moving to a more service style pattern similar to the one used in the service layer for our Apps results in those VM&#8217;s which need to use the favourites service have this injected during startup via the bootstrapper. Unlike our current situation where each VM has to register for the message. This gets us back into check with a single responsibility pattern. As the favourites service is now responsible for anything to do with favourites cleaning up the implementation code in the VM&#8217;s wanting to use the service. Sweet!<a href="http://blogs.xamlninja.com/wp-content/uploads/2011/02/servicestyleratherthanmessenger.png" rel="shadowbox[sbpost-358];player=img;" target="_blank"><img class="alignright size-full wp-image-374" style="margin: 5px;" title="servicestyleratherthanmessenger" src="http://blogs.xamlninja.com/wp-content/uploads/2011/02/servicestyleratherthanmessenger.png" alt="" width="354" height="629" /></a></p>
<p>Now I really like this pattern as its super simple to implement and by taking advantage of IStorage and IStorageService which can be found in the WP7C not only do we have a simple pattern for sharing data and operating on that data, we also get the ability to stash this content into Isolated Storage.</p>
<p>The best way for me to show this off is to do a sample, so I am going to build on the sample from the previous post, its also in the spikes directory on <a href="http://wp7contrib.codeplex.com/" target="_blank">Codeplex</a>. What we are going to add to this is a favourites page, wired up to a Favourites VM, and a favourites service that has the ability for our user to do an add to favourites from the list (Main VM)and an add to favourites from the details page (Child VM).</p>
<p>First, up we need to create an interface, in my case its called IFavouriteSearch and it going to provide a service to retrieve the current collection of favourites, add a new favourite, query to see if the service already contains a particular favourite and also remove a favourite from the collection.</p>
<pre class="brush: csharp">
using ServiceStyleRatherThanMessengerStyle.Model;

using WP7Contrib.Collections;

/// &lt;summary&gt;
/// The favourites service contract.
/// &lt;/summary&gt;
public interface IFavouritesService
{
        #region Properties

        /// &lt;summary&gt;
        /// Gets Favourites.
        /// &lt;/summary&gt;
        ReadOnlyObservableCollection&lt;Person&gt; Favourites { get; }

        #endregion

        #region Public Methods

        /// &lt;summary&gt;
        /// The add.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;person&quot;&gt;
        /// The currently selected person.
        /// &lt;/param&gt;
        void Add(Person person);

        /// &lt;summary&gt;
        /// The is a favourite.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;person&quot;&gt;
        /// The person.
        /// &lt;/param&gt;
        /// &lt;returns&gt;
        /// The is a favourite.
        /// &lt;/returns&gt;
        bool IsAFavourite(Person person);

        /// &lt;summary&gt;
        /// The remove favoutite.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;person&quot;&gt;
        /// The person.
        /// &lt;/param&gt;
        void RemoveFavourite(Person person);

        #endregion
}
</pre>
<p>That’s the service defined.</p>
<p>Next up we need to define a concrete class called the Favourite Service which implements the interface, the important part to remember here is that we want to stash the collection to isolated storage in order to persist the selected favourites between sessions. In order to do this we can simply pass into the constructor the IStorageService interface, if you wanted to use the logging parts of <a href="http://wp7contrib.codeplex.com/" target="_blank">WP7C</a> then you can added this into the constructor parameter list.</p>
<pre class="brush: csharp">
public FavouritesService(IStorageService storageService, ILog log)
{
   this.storageService = storageService;
   this.log = log;
}
</pre>
<p>So this is the cool part, when we expose the favourites collection all we need to do is work out if we are rehydrating the collection for the first time from Isolated Storage and load up the collection in ISO, otherwise we new up a collection of the required type. Each piece of content that is stored into ISO has its own key, in my case its called favourites and its used as the Unique ID to retrieve the specified content. The code to Load from Storage is boiler plate and done once it’s a rinse and repeat style pattern.</p>
<pre class="brush: csharp">
/// &lt;summary&gt;
/// Gets Favourites.
/// &lt;/summary&gt;
public ReadOnlyObservableCollection&lt;Person&gt; Favourites
{
   get
   {
      if (!this.loaded)
      {
         this.LoadFromStorage();
      }

       return new ReadOnlyObservableCollection&lt;Person&gt;(this.favourites);
   }
}
</pre>
<p>The management methods that operate on the collection we build out as normal and then decorate this code with the storage calls. These are rather easy to remember; once the collection has been updated then we make a call to write the list into ISO associated with our Unique ID, then we flush the storage buffer.</p>
<pre class="brush: csharp">
/// &lt;summary&gt;
/// Adds a person to the favourites.
/// &lt;/summary&gt;
/// &lt;param name=&quot;person&quot;&gt;
/// The currently selected person.
/// &lt;/param&gt;
public void Add(Person person)
{
   if (person == null)
   {
      return;
   }

   if (!this.loaded)
   {
      this.LoadFromStorage();
   }

   if (this.favourites.Contains(person))
   {
      return;
   }

   this.favourites.Add(person);
   this.storage.Write(StorageKey, this.favourites.ToList());
   this.storage.Flush();
}

/// &lt;summary&gt;
/// The is a favourite.
/// &lt;/summary&gt;
/// &lt;param name=&quot;person&quot;&gt;
/// The person.
/// &lt;/param&gt;
/// &lt;returns&gt;
/// Returns true if the person is a favourite.
/// &lt;/returns&gt;
public bool IsAFavourite(Person person)
{
   if (person == null)
   {
      return false;
   }

   if (!this.loaded)
   {
      this.LoadFromStorage();
   }

   return this.favourites.Contains(person);
}

/// &lt;summary&gt;
/// The remove favoutite.
/// &lt;/summary&gt;
/// &lt;param name=&quot;person&quot;&gt;
/// The persoh.
/// &lt;/param&gt;
public void RemoveFavourite(Person person)
{
   if (person == null)
   {
      return;
   }

   if (!this.loaded)
   {
      this.LoadFromStorage();
   }

   if (!this.favourites.Contains(person))
   {
      return;
   }

   this.favourites.Remove(persoh);
   this.storage.Write(StorageKey, this.favourites);
   this.storage.Flush();
}
</pre>
<p>Lets now take a look at the Load From Storage method.</p>
<pre class="brush: csharp">
/// &lt;summary&gt;
/// The load from storage.
/// &lt;/summary&gt;
private void LoadFromStorage()
{
   if (this.loaded)
   {
      return;
   }

   lock (this.sync)
   {
      if (this.loaded)
      {
         return;
      }

      this.favourites = new ObservableCollection&lt;Person&gt;();
      this.storage = this.storageService.OpenPersistent(StorageKey);

      var favs = this.storage.Read&lt;List&lt;Person&gt;&gt;(StorageKey);
      if (favs == null || favs.Count == 0)
      {
         this.log.Write(&quot;FavouritesService: No favourites&quot;);
      }
      else
      {
         foreach (Person fav in favs)
         {
              this.log.Write(&quot;FavouritesService: Loading Person, hash code - &quot; + fav.GetHashCode());
              this.favourites.Add(fav);
         }
     }

      this.loaded = true;
   }
}
</pre>
<p>When we need to read the collection we use the Storage service to setup the storage mechanism once this has been done happy days simply call the Read method telling what type is being rehydrated using the specified  Unique key that was defined earlier. Iterate over what comes out and add it to our collection.</p>
<p>Now we need to be able to use the service so we head over to the bootstrapper and crank out some register and resolve calls for the service.</p>
<pre class="brush: csharp">
this.Container.Register&lt;ILogManager&gt;(c =&gt; new LoggingService(&quot;LastReplayMessenger&quot;));

this.Container.Register&lt;ILog&gt;(c =&gt; this.Container.Resolve&lt;ILogManager&gt;());

var assemblies = new List&lt;Assembly&gt; { this.GetType().Assembly, typeof(BaseModel).Assembly };

this.Container.Register&lt;IStorageService&gt;(c =&gt; new StorageService(c.Resolve&lt;ILog&gt;(), assemblies));

this.Container.Register&lt;IFavouritesService&gt;(
c =&gt; new FavouritesService(c.Resolve&lt;IStorageService&gt;(), c.Resolve&lt;ILog&gt;()));
</pre>
<p>And that’s our service registered and resolved, our next step is to inject the favourite service into the VM&#8217;s that are going to be using it.</p>
<pre class="brush: csharp">
this.Container.Register(
c =&gt;
new MainViewModel(
c.Resolve&lt;INavigationService&gt;(),
c.Resolve&lt;IMessenger&gt;(),
c.Resolve&lt;ILog&gt;(),
c.Resolve&lt;IFavouritesService&gt;()));

this.Container.Register(
c =&gt;
new ChildViewModel(
c.Resolve&lt;INavigationService&gt;(),
c.Resolve&lt;IMessenger&gt;(),
c.Resolve&lt;ILog&gt;(),
c.Resolve&lt;IFavouritesService&gt;()));
</pre>
<p>A common scenario is that we have a View which provides an experience that allows the user to add items via a list. In my case I choose a context menu which was added to the data template used by the list box. In order to do this I created a Relay Command and wired this up to the context menu from the toolkit in the data template. There are two implementations that we need to implement here first we need to be able to trigger a command from inside the data template of the listbox.</p>
<pre class="brush: csharp">
/// &lt;summary&gt;
/// The select add to favourites command.
/// &lt;/summary&gt;
private RelayCommand&lt;Person&gt; selectAddToFavouritesCommand;

/// &lt;summary&gt;
/// Gets SelectAddToFavouritesCommand.
/// &lt;/summary&gt;
public RelayCommand&lt;Person&gt; SelectAddToFavouritesCommand
{
   get
   {
      return this.selectAddToFavouritesCommand ??
      (this.selectAddToFavouritesCommand = new RelayCommand&lt;Person&gt;(this.ExecuteAddToFavouritesCommand));
   }

   private set
   {
      this.selectAddToFavouritesCommand = value;
   }
}

/// &lt;summary&gt;
/// The execute add to favourites command.
/// &lt;/summary&gt;
/// &lt;param name=&quot;person&quot;&gt;
/// The person.
/// &lt;/param&gt;
private void ExecuteAddToFavouritesCommand(Person person)
{
   this.favouritesService.Add(person);
}
</pre>
<pre class="brush: xml">
&lt;toolkit:ContextMenuService.ContextMenu&gt;
&lt;toolkit:ContextMenu&gt;
&lt;toolkit:MenuItem Header=&quot;add to favourites&quot;
Command=&quot;{Binding MainViewModel.SelectAddToFavouritesCommand, Source={StaticResource Locator}}&quot;
CommandParameter=&quot;{Binding .}&quot; /&gt;
&lt;/toolkit:ContextMenu&gt;
&lt;/toolkit:ContextMenuService.ContextMenu&gt;
</pre>
<p>And the other implementation is from an app bar button.</p>
<pre class="brush: csharp">
/// &lt;summary&gt;
/// The execute add to favourites command.
/// &lt;/summary&gt;
private void ExecuteAddToFavouritesCommand()
{
   this.favouritesService.Add(this.CurrentlySelectedPerson);
   this.NavigationService.Navigate(new Uri(&quot;/View/FavouritesPage.xaml&quot;, UriKind.Relative));
}
</pre>
<pre class="brush: xml">
&lt;phone:PhoneApplicationPage.ApplicationBar&gt;
&lt;shell:ApplicationBar IsVisible=&quot;True&quot;
IsMenuEnabled=&quot;True&quot;&gt;
&lt;shell:ApplicationBarIconButton x:Name=&quot;AddToFavourites&quot;
IconUri=&quot;/resources/icons/appbar.favs.addto.rest.png&quot;
Text=&quot;AddToFavourites&quot; /&gt;
&lt;/shell:ApplicationBar&gt;
&lt;/phone:PhoneApplicationPage.ApplicationBar&gt;

&lt;i:Interaction.Behaviors&gt;
&lt;Behaviors:ApplicationBarIconButtonCommand TextKey=&quot;AddToFavourites&quot;
CommandBinding=&quot;{Binding SelectAddToFavouritesCommand}&quot; /&gt;
&lt;/i:Interaction.Behaviors&gt;
</pre>
<p>Lets just quickly circle back, what we have done thus far is implement the required add to favourites functionality, but ultimately we also want to allow the user to view their favourites so next we need to create the page and the favourites VM remembering to add the new VM to the VM Locator.</p>
<p>The favourites VM.</p>
<pre class="brush: csharp">
/// &lt;summary&gt;
/// The favourites view model.
/// &lt;/summary&gt;
public class FavouritesViewModel : ViewModelBaseWp7
{
    #region Constants and Fields

    /// &lt;summary&gt;
    /// The favourites service.
    /// &lt;/summary&gt;
    private readonly IFavouritesService favouritesService;

    /// &lt;summary&gt;
    /// The currently selected person.
    /// &lt;/summary&gt;
    private Person currentlySelectedPerson;

    #endregion

    #region Constructors and Destructors

    /// &lt;summary&gt;
    /// Initializes a new instance of the &lt;see cref=&quot;FavouritesViewModel&quot;/&gt; class.
    /// &lt;/summary&gt;
    /// &lt;param name=&quot;navigationService&quot;&gt;
    /// The navigation service.
    /// &lt;/param&gt;
    /// &lt;param name=&quot;messenger&quot;&gt;
    /// The messenger.
    /// &lt;/param&gt;
    /// &lt;param name=&quot;log&quot;&gt;
    /// The log.
    /// &lt;/param&gt;
    /// &lt;param name=&quot;favouritesService&quot;&gt;
    /// The favourites service.
    /// &lt;/param&gt;
    public FavouritesViewModel(
        INavigationService navigationService, IMessenger messenger, ILog log, IFavouritesService favouritesService)
        : base(navigationService, messenger, log)
    {
        this.favouritesService = favouritesService;

        ThreadPool.QueueUserWorkItem(
            state =&gt; { this.MessengerInstance.Register&lt;SelectedPersonMessage&gt;(this, this.OnReceiveMessage); });
    }

    #endregion

    /// &lt;summary&gt;
    /// Gets CurrentlySelectedCurrentlySelectedPerson.
    /// &lt;/summary&gt;
    public Person CurrentlySelectedPerson
    {
        get
        {
            return this.currentlySelectedPerson;
        }

        private set
        {
            this.SetPropertyAndNotify(ref this.currentlySelectedPerson, value, &quot;CurrentlySelectedPerson&quot;);
        }
    }

    public ReadOnlyObservableCollection&lt;Person&gt; Favourites
    {
        get
        {
            return this.favouritesService.Favourites;
        }
    }

    #region Methods

    private void OnReceiveMessage(SelectedPersonMessage obj)
    {
        if (obj == null)
        {
            return;
        }

        if (obj.Person == null)
        {
            return;
        }

        this.CurrentlySelectedPerson = obj.Person;
    }

    /// &lt;summary&gt;
    /// The is being activated.
    /// &lt;/summary&gt;
    /// &lt;param name=&quot;storage&quot;&gt;
    /// The storage.
    /// &lt;/param&gt;
    protected override void IsBeingActivated(IStorage storage)
    {
    }

    /// &lt;summary&gt;
    /// The is being deactivated.
    /// &lt;/summary&gt;
    /// &lt;param name=&quot;storage&quot;&gt;
    /// The storage.
    /// &lt;/param&gt;
    protected override void IsBeingDeactivated(IStorage storage)
    {
    }

    #endregion
}
</pre>
<p>And the favourites page which has a listbox data bound to the favourites collection exposed by the VM.</p>
<pre class="brush: xml">
&lt;Grid x:Name=&quot;ContentPanel&quot;
Grid.Row=&quot;1&quot;
Margin=&quot;12,0,12,0&quot;&gt;
&lt;ListBox ItemsSource=&quot;{Binding Path=Favourites}&quot;
SelectedItem=&quot;{Binding Path=CurrentlySelectedPerson}&quot;
ItemTemplate=&quot;{StaticResource PersonsDataTemplate}&quot;
ItemContainerStyle=&quot;{StaticResource ListBoxItemStyle1}&quot; /&gt;
&lt;/Grid&gt;
</pre>
<p>And we are done!</p>
<p>One thing that I did add here is the Last Replay Message Messenger and data binding to the selected item in the listbox so that I can highlight the newly added favourite.</p>
<p>A quick recap on what happened</p>
<ol>
<li>Create the interface for the service and expose what you need usually a collection and some management methods for managing the data</li>
<li>Create the concrete implementation adding in the IStorageService into the constructor</li>
<li>In the concrete add logic to rehydrate and stash your data</li>
<li>Update the constructor on the VM&#8217;s that need to have the add to favourites functionality</li>
<li>In the Bootstrapper register the new service  and Resolve them in the VM&#8217;s</li>
<li>Create relay commands in the VM and View to trigger the actions</li>
<li>Create the favourites page and VM</li>
<li>Update the Bootstrapper and VM Locator with the new VM</li>
<li>Expose a property for the collection so that it can be bound to in the View</li>
<li>[Optional] use the Last Replay Message to inform the favourites VM about the currently selected person</li>
</ol>
<p>What is very interesting about all this is that we so often when using a framework get familiar with a certain technique and this becomes fashionable and we try to use it everywhere and there is nothing wrong with trying out new ways of doing something. However, there also has to be a realisation that when we start getting friction trying to bend the framework api to do something that it was not really meant for its time to use something solves the problem better.</p>
<p>Interested in your comments and you can find the code up on <a href="http://wp7contrib.codeplex.com/">codeplex</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.xamlninja.com/mvvm/wp7-contrib-when-messaging-becomes-messy-and-services-shine/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>MVVM, design time data, and Blendability</title>
		<link>http://blogs.xamlninja.com/silverlight/mvvm-design-time-data-and-blendability</link>
		<comments>http://blogs.xamlninja.com/silverlight/mvvm-design-time-data-and-blendability#comments</comments>
		<pubDate>Fri, 02 Oct 2009 08:44:15 +0000</pubDate>
		<dc:creator>rich</dc:creator>
				<category><![CDATA[Blend]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[Ninject]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[Xaml]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://blogs.xamlninja.com/?p=34</guid>
		<description><![CDATA[With the introduction of design time data support in Blend I thought that I would try and take advantage of using design time data and MVVM. For a while now I have been using Ninject, with a Service Locator Pattern to provide the ability to build WPF and Silverlight apps in an MVVM pattern where [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://blogs.xamlninja.com/wp-content/uploads/2009/10/Designtimedataprojectstructure1.PNG" alt="Designtimedataprojectstructure" title="Designtimedataprojectstructure" width="444" height="450" class="alignleft size-full wp-image-84" />With the introduction of design time data support in Blend I thought that I would try and take advantage of using design time data and MVVM. For a while now I have been using Ninject, with a Service Locator Pattern to provide the ability to build WPF and Silverlight apps in an MVVM pattern where I prefer to use a View first mechanism. There are a number of benefits from using this approach, one of the ones that we are good to drill to in this post is around Blendability of the controls that developers create. Prior to me using Ninject I would have a heavy reliance on the DesignerProperties IsInDesignMode call to check to see if the control was being render in Blend, as i would normally have to do something to stop the control from crashing and allow myself and the designer to use Blend in order for us to Style and Template the controls we created.</p>
<p>What we are going to cover here is the journey which i went on when adding support for design time data to my project, I really like it as the refactoring from the standard inbuilt mechanism in Blend to the final output is a nice series of steps that feel good.<br />
<a href="http://blogs.xamlninja.com/wp-content/uploads/2009/10/Designtimedata.png" rel="shadowbox[sbpost-34];player=img;"><img style="border-right-width: 0px; margin: 10px 5px 10px 10px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="Designtimedata" src="http://blogs.xamlninja.com/wp-content/uploads/2009/10/Designtimedata_thumb.png" border="0" alt="Designtimedata" width="395" height="276" align="right" /></a></p>
<p>The screen shot on the right shows the simple looking UI displaying contextual data in Blend allowing the designer to see how the control will look. I think providing the ability for your application to look exactly the same at design time as at run time is going to mean that you can produce better looking applications quicker as the designer is design the screens in the context of the data.</p>
<p>When first adding the design time data to your project Blend takes over control and this means that you need to use Blend to shape your design time data classes to match your data types used in the system. So if we were building a throw away prototype then I would agree this is the best way forwards, but when you are moving from prototype to production this does not really work. On of the reasons behind the research for this post is around the transition from prototype to production and even from sketch to prototype, once we have sign off from the client on a number of ideas and we want to start to build these out then there is a high potential one will become production quality and because of this its good to have the right architecture in place, so reshaping to MVVM early on will almost certainly cost your client less.</p>
<p>The Xaml below is what i put together to represent the shape of data that was in the mock classes. Blend then hooks this data up to the design time data context for you.</p>
<p>Xaml data for shopping cart</p>
<pre class="brush: xml">
&lt;local:ShoppingCartViewModel xmlns:local=&quot;clr-namespace:DesignDataSample;assembly=DesignDataSample&quot;&gt;
    &lt;local:ShoppingCartViewModel.ShoppingCart xmlns:local=&quot;clr-namespace:DesignDataSample;assembly=DesignDataSample&quot;&gt;
        &lt;local:ShoppingCart&gt;
            &lt;local:ShoppingCart.Items&gt;
                &lt;local:ShoppingCartItem ItemName=&quot;Book Name 1&quot;
                                        ItemDescription=&quot;A very nice book!&quot;
                                        ItemImage=&quot;MySampleDataImages/Tree.jpg&quot; /&gt;
                &lt;local:ShoppingCartItem ItemName=&quot;Book Name 2&quot;
                                        ItemDescription=&quot;A very nice book!&quot;
                                        ItemImage=&quot;MySampleDataImages/Tree.jpg&quot; /&gt;
                &lt;local:ShoppingCartItem ItemName=&quot;Book Name 3&quot;
                                        ItemDescription=&quot;A very nice book!&quot;
                                        ItemImage=&quot;MySampleDataImages/Tree.jpg&quot; /&gt;
                &lt;local:ShoppingCartItem ItemName=&quot;Book Name 4&quot;
                                        ItemDescription=&quot;A very nice book!&quot;
                                        ItemImage=&quot;MySampleDataImages/Tree.jpg&quot; /&gt;
            &lt;/local:ShoppingCart.Items&gt;
        &lt;/local:ShoppingCart&gt;
    &lt;/local:ShoppingCartViewModel.ShoppingCart&gt;
&lt;/local:ShoppingCartViewModel&gt;
</pre>
<p>When the design time data shape matches your real data shape you can then go ahead and use the new d:DataContext Dependency Property and bind your design time data to this property.</p>
<p>Xaml Source code for the control</p>
<pre class="brush: xml">
&lt;UserControl
        xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
             xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
             xmlns:d=&quot;http://schemas.microsoft.com/expression/blend/2008&quot;
             xmlns:mc=&quot;http://schemas.openxmlformats.org/markup-compatibility/2006&quot;
             mc:Ignorable=&quot;d&quot;
             x:Class=&quot;DesignDataSample.ShoppingCartView&quot;
             d:DataContext=&quot;{d:DesignData Source=ShoppingCartSampleData.xaml}&quot;
             DataContext=&quot;{Binding Path=ShoppingCartViewModel, Source={StaticResource serviceLocator}}&quot;
             Height=&quot;347&quot;
             Width=&quot;494&quot;&gt;
</pre>
<p>Nothing too tricky there, the new design time data context is the key to making all this happen, it also means that you can bind any sort of data you want to the design time data context to provide contextual data in Blend during design time. It was at this point that i started to think about how we can really bend the design time data features. My initial refactor was not a great result in that I ended up with 2 sets of mock data; one set of data would be used by the designers in Blend; and the second set of data would be used by the unit test, Not nice, management nightmare to ensure that both data sets are keep in sync.</p>
<p>So the goal was to provide design time data which was the same data used by the unit tests, meaning that we only have one data set to maintain and manage, allowing us to leverage the powerful features of design time data in Blend and also keeping our unit tests looking sweet, pleasing both the designers and the developers on the team.</p>
<p>In order to do this I needed to restructure the existing shape of my data classes that I use in my mock service layer classes, first I needed to change the OnCompleted method to be a virtual implementation and also the method which retrieves the data. This simple change means that we can now provide two mock services that can be injected in.</p>
<p>Refactored mock service class with new virtual methods</p>
<pre class="brush: csharp">
    using System;
    using System.Collections.ObjectModel;

    public class MockShoppingCartService : IShoppingCartService
    {
        public event GetShoppingCartCompletedHandler GetShoppingCartCompleted;

        public bool LoginToShoppingCart(string username, string password)
        {
            throw new System.NotImplementedException();
        }

        public virtual void RetrieveShoppingCart()
        {
            this.OnGetShoppingCartCompleted(null, MockShoppingCartData.CreateShoppingCartRuntime());
        }

        protected virtual void OnGetShoppingCartCompleted(Exception error, ShoppingCart result)
        {
            if (this.GetShoppingCartCompleted != null)
            {
                this.GetShoppingCartCompleted(new GetShoppingCartCompletedEventArgs(error, result));
            }
        }
    }
</pre>
<p>The new mock service class which is used specifically for working with Blend</p>
<pre class="brush: csharp">
namespace DesignDataSample.Mocks
{
    public class MockShoppingCartServiceDesignData : MockShoppingCartService
    {
        public override void RetrieveShoppingCart()
        {
            this.OnGetShoppingCartCompleted(null, MockShoppingCartData.CreateShoppingCartDesigntime());
        }
    }
}
</pre>
<p>How we can use ninject to inject the service we want to use, design time data, mock or real.</p>
<pre class="brush: csharp">
this.Bind&lt;IShoppingCartService&gt;().To&lt;MockShoppingCartService&gt;().OnlyIf(c =&gt; isBrowser);
this.Bind&lt;IShoppingCartService&gt;().To&lt;MockShoppingCartServiceDesignData&gt;().OnlyIf(c =&gt; isBlend);
this.Bind&lt;IShoppingCartService&gt;().To&lt;ShoppingCartService&gt;().OnlyIf(c =&gt; isBrowser);
this.Bind&lt;ShoppingCartViewModel&gt;().ToSelf();
</pre>
<p>Xaml code for how we leverage the data context and the new design time data context for providing contextual data.</p>
<pre class="brush: xml">
&lt;UserControl
        xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
             xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
             xmlns:d=&quot;http://schemas.microsoft.com/expression/blend/2008&quot;
             xmlns:mc=&quot;http://schemas.openxmlformats.org/markup-compatibility/2006&quot;
             mc:Ignorable=&quot;d&quot;
             x:Class=&quot;DesignDataSample.ShoppingCartView&quot;
             d:DataContext=&quot;{Binding Path=ShoppingCartViewModel, Source={StaticResource serviceLocator}}&quot;
             DataContext=&quot;{Binding Path=ShoppingCartViewModel, Source={StaticResource serviceLocator}}&quot; Height=&quot;347&quot; Width=&quot;494&quot;&gt;
&lt;!--d:DataContext=&quot;{d:DesignData Source=ShoppingCartSampleData.xaml}&quot;--&gt;
    &lt;UserControl.Resources&gt;
        &lt;DataTemplate x:Key=&quot;ShoppingCartItemTemplate&quot;&gt;
            &lt;Grid Height=&quot;50&quot;&gt;
                &lt;Grid.ColumnDefinitions&gt;
                    &lt;ColumnDefinition Width=&quot;50&quot; /&gt;
                    &lt;ColumnDefinition Width=&quot;*&quot; /&gt;
                &lt;/Grid.ColumnDefinitions&gt;
                &lt;Grid.RowDefinitions&gt;
                    &lt;RowDefinition Height=&quot;*&quot; /&gt;
                    &lt;RowDefinition Height=&quot;*&quot; /&gt;
                &lt;/Grid.RowDefinitions&gt;

                &lt;Image Source=&quot;{Binding ItemImage}&quot;
                       Grid.RowSpan=&quot;2&quot; /&gt;
                &lt;TextBlock Text=&quot;{Binding ItemName}&quot;
                           Grid.Column=&quot;1&quot;
                           Margin=&quot;4,0,0,0&quot; /&gt;
                &lt;TextBlock Text=&quot;{Binding ItemDescription}&quot;
                           Grid.Column=&quot;1&quot;
                           Grid.Row=&quot;1&quot;
                           Margin=&quot;4,0,0,0&quot; /&gt;
            &lt;/Grid&gt;
        &lt;/DataTemplate&gt;
    &lt;/UserControl.Resources&gt;

    &lt;Grid x:Name=&quot;LayoutRoot&quot;
          Background=&quot;#FFB2B2B2&quot;&gt;
        &lt;Grid.ColumnDefinitions&gt;
            &lt;ColumnDefinition /&gt;
            &lt;ColumnDefinition Width=&quot;129&quot; /&gt;
            &lt;ColumnDefinition Width=&quot;121&quot; /&gt;
        &lt;/Grid.ColumnDefinitions&gt;
        &lt;Grid.RowDefinitions&gt;
            &lt;RowDefinition /&gt;
            &lt;RowDefinition Height=&quot;50&quot; /&gt;
        &lt;/Grid.RowDefinitions&gt;
        &lt;ListBox Margin=&quot;8,8,8,26&quot;
                 Grid.ColumnSpan=&quot;3&quot;
                 ItemsSource=&quot;{Binding Mode=OneWay, Path=ShoppingCart.Items}&quot;
                 ItemTemplate=&quot;{StaticResource ShoppingCartItemTemplate}&quot; /&gt;
        &lt;TextBlock Grid.Row=&quot;1&quot;
                   Text=&quot;Total Items:&quot;
                   TextWrapping=&quot;Wrap&quot;
                   Grid.Column=&quot;1&quot; /&gt;
        &lt;TextBlock Grid.Column=&quot;2&quot;
                   Grid.Row=&quot;1&quot;
                   Text=&quot;{Binding ShoppingCart.Items.Count}&quot;
                   TextWrapping=&quot;Wrap&quot; /&gt;
    &lt;/Grid&gt;
&lt;/UserControl&gt;</pre>
<p> </p>
<p>So I hope that this article has opened your eyes to how useful design time data can be to enhance the Blendability of the controls which you produce both lookless and user. In the majority of cases designers that you are working with really like that they can view the control at deign time how it will appear when running in your application and populated with data.  When implementing the MVVM pattern in you application incorporating support for design time data is also possible and provides you with the ultimate Xaml Ninja experience.</p>
<p>You can download the source from my Skydrive.</p>
<p><iframe title ="Preview" scrolling="no" marginheight="0" marginwidth="0" frameborder="0" style="width:98px;height:115px;padding:0;background-color:#fcfcfc;" src="http://cid-118ee1873690fc1d.skydrive.live.com/embedicon.aspx/Silverlight3/DesignData/DesignDataSample.zip"></iframe></p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.xamlninja.com/silverlight/mvvm-design-time-data-and-blendability/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

