<?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; Xaml</title>
	<atom:link href="http://blogs.xamlninja.com/tag/xaml/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>Metro Controls &#8211; Jump Viewer</title>
		<link>http://blogs.xamlninja.com/xaml/metro-controls-jump-viewer</link>
		<comments>http://blogs.xamlninja.com/xaml/metro-controls-jump-viewer#comments</comments>
		<pubDate>Fri, 30 Sep 2011 18:23:49 +0000</pubDate>
		<dc:creator>rich</dc:creator>
				<category><![CDATA[Metro]]></category>
		<category><![CDATA[Xaml]]></category>
		<category><![CDATA[winrt]]></category>

		<guid isPermaLink="false">http://blogs.xamlninja.com/?p=740</guid>
		<description><![CDATA[After an amazing week at //Build, I&#8217;ve been busy playing with the new controls, which I have to say are fantastic! Ollie and I know the pain first hand when it comes to building a Silverlight TUI (Touch User Interface) it&#8217;s not a great story and IMHO the controls are not ready. I may still [...]]]></description>
			<content:encoded><![CDATA[<p>After an amazing week at //Build, I&#8217;ve been busy playing with the new controls, which I have to say are fantastic! <a href="http://awkwardcoder.blogspot.com/" target="_blank">Ollie </a>and I know the pain first hand when it comes to building a Silverlight TUI (Touch User Interface) it&#8217;s not a great story and IMHO the controls are not ready. I may still post my thoughts on this experience, I&#8217;ve been holding back as I really don&#8217;t want to be dragged into the Silverlight is DEAD! debacle and this post could be taken in this way, however it will give you context around why we are so pleased that there is a new story and that one is awesome. But while I think about posting my experiences of building TUI on slates running Win 7, I&#8217;ve been putting together notes on the controls and thought that these may be beneficial to others so my objectives are to walk through some of the new controls and peel the layers like an onion. So, we can then go deep on certain topics.</p>
<p>So without further ado please say a big HELLO! to the Jump Viewer which is currently my favourite control. The interactions are stunning and performance is awesome! Before I start to dig in we should take a look at the finished control. The first screen shot is of the Jump Viewer when it first loads up in its zoomed in state and the second screen shot is taken when we peform an inwards pinch gesture which zooms out and the semantic zoom kicks in replacing the view with higher level details so that we can easily jump to another position in the Grid.</p>
<p><a href="http://blogs.xamlninja.com/wp-content/uploads/2011/09/JumpViewer1.png" rel="shadowbox[sbpost-740];player=img;"><img class="alignleft size-large wp-image-742" title="JumpViewer1" src="http://blogs.xamlninja.com/wp-content/uploads/2011/09/JumpViewer1-1024x574.png" alt="" width="1024" height="574" /></a></p>
<p>&nbsp;</p>
<p><a href="http://blogs.xamlninja.com/wp-content/uploads/2011/09/JumpViewer2.png" rel="shadowbox[sbpost-740];player=img;"><img class="alignleft size-full wp-image-743" title="JumpViewer2" src="http://blogs.xamlninja.com/wp-content/uploads/2011/09/JumpViewer2.png" alt="" width="813" height="763" /></a></p>
<p>&nbsp;</p>
<p>Note:- there are some anti-aliasing issues that happen periodically, not sure why this happens but I will update the post when I know more.</p>
<p>&nbsp;</p>
<p>For more background reading on semantic zoom check out <a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh465319%28v=vs.85%29.aspx" target="_blank">the guidelines for semantic zoom</a> and also the <a href="http://code.msdn.microsoft.com/windowsapps/Semantic-zoom-sample-2ca01adf" target="_blank">sample in the SDK</a>.</p>
<p>What I really like about the Jump Viewer is that it uses composition, allowing you to simply wrap up other controls that you may have used previously in order to deliver an immersive experience when interacting with the visualised data. In order to build a better understanding of the control we need to look at the Xaml. Lets start by concentrating on the JumpView which is the part of the control that is activated when we zoom out.</p>
<p>I have added my notes into the Xaml and hopefully this is a better way of groking the Xaml rather than snippets and dialogue, this way you can copy and paste the Xaml into your app and retain the notes.</p>
<pre class="brush: xml">

 &lt;!--
The jump view is the visual effect when we use semantic zoom the pinch-in gesture
The grid view items panel is set to a wrapgrid
Which renders a list of category names
--&gt;
&lt;JumpViewer x:Name=&quot;jumpViewer&quot;
        Grid.Row=&quot;1&quot;
        Margin=&quot;120,0,0,0&quot;&gt;
        &lt;!--
        The jump viewer jump view
        --&gt;
        &lt;JumpViewer.JumpView&gt;
                &lt;GridView Foreground=&quot;White&quot;&gt;
                &lt;GridView.ItemTemplate&gt;
                &lt;!--
                Data template used to visualise what we want to display when zoomed out
                In our case we are showing some group text
                --&gt;
                &lt;DataTemplate&gt;
                        &lt;TextBlock Text=&quot;{Binding Name}&quot;
                        FontFamily=&quot;{StaticResource SemiBoldContentFontFamily}&quot;
                        FontSize=&quot;{StaticResource HeaderLargeFontSize}&quot;
                        Foreground=&quot;{StaticResource PageForegroundBrush}&quot; /&gt;
                &lt;/DataTemplate&gt;
                &lt;/GridView.ItemTemplate&gt;
                &lt;GridView.ItemsPanel&gt;
                        &lt;ItemsPanelTemplate&gt;
                            &lt;!--
                                Positions child elements sequentially from left to right or top to bottom.
                                When elements extend beyond the container edge, elements are positioned in the next row or column.
                                You can change the Maximum rows or columns to change the visual layout when zoomed out
                            --&gt;
                            &lt;WrapGrid ItemWidth=&quot;114&quot;
                                      ItemHeight=&quot;114&quot;
                                      MaximumRowsOrColumns=&quot;6&quot;
                                      VerticalChildrenAlignment=&quot;Center&quot; /&gt;
                        &lt;/ItemsPanelTemplate&gt;
                &lt;/GridView.ItemsPanel&gt;
                &lt;!--
                Note when we change the item container style the target type is ListViewItem not GridViewItem
                --&gt;
                &lt;GridView.ItemContainerStyle&gt;
                    &lt;Style TargetType=&quot;ListViewItem&quot;&gt;
                        &lt;Setter Property=&quot;Margin&quot;
                                Value=&quot;6&quot; /&gt;
                        &lt;Setter Property=&quot;Padding&quot;
                                Value=&quot;12&quot; /&gt;
                        &lt;Setter Property=&quot;BorderBrush&quot;
                                Value=&quot;{StaticResource PageForegroundBrush}&quot; /&gt;
                        &lt;Setter Property=&quot;BorderThickness&quot;
                                Value=&quot;1&quot; /&gt;
                        &lt;Setter Property=&quot;HorizontalContentAlignment&quot;
                                Value=&quot;Center&quot; /&gt;
                        &lt;Setter Property=&quot;VerticalContentAlignment&quot;
                                Value=&quot;Center&quot; /&gt;
                    &lt;/Style&gt;
                &lt;/GridView.ItemContainerStyle&gt;
                &lt;/GridView&gt;
            &lt;/JumpViewer.JumpView&gt;
</pre>
<p>Below is an illustration of the above Xaml and how the composite parts fit together.</p>
<p><a href="http://blogs.xamlninja.com/wp-content/uploads/2011/09/JumpViewerJumpView.png" rel="shadowbox[sbpost-740];player=img;"><img class="alignleft size-full wp-image-744" title="JumpViewerJumpView" src="http://blogs.xamlninja.com/wp-content/uploads/2011/09/JumpViewerJumpView.png" alt="" width="487" height="457" /></a><br />
&nbsp;<br />
&nbsp;<br />
&nbsp;<br />
&nbsp;<br />
&nbsp;<br />
&nbsp;<br />
&nbsp;<br />
&nbsp;<br />
&nbsp;<br />
&nbsp;<br />
&nbsp;<br />
&nbsp;<br />
&nbsp;<br />
&nbsp;<br />
&nbsp;<br />
&nbsp;<br />
&nbsp;<br />
&nbsp;<br />
&nbsp;<br />
&nbsp;<br />
&nbsp;<br />
&nbsp;</p>
<p>What is very cool is the new Wrap Grid which provides the ability to change the layout of Jump View in the code above I do this.</p>
<pre class="brush: xml">
&lt;WrapGrid ItemWidth=&quot;114&quot;
    ItemHeight=&quot;114&quot;
    MaximumRowsOrColumns=&quot;6&quot;
    VerticalChildrenAlignment=&quot;Center&quot; /&gt;
</pre>
<p>In order to change the layout of the grid we can simply change the number of Maximum Rows or Columns, for example changing this property to 1 will change the layout to look more like the standard search control in Metro. Therefore, a quick tweak with how many rows or columns you want means that you can change the experience depending on the content being visualised. I will cover off the Wrap Grid in a future post.</p>
<p>Next we need to look at the content part of the Jump Viewer.</p>
<pre class="brush: xml">
&lt;!--
    The content view renders the detailed items
--&gt;
&lt;JumpViewer.ContentView&gt;
    &lt;GridView ItemsSource=&quot;{Binding Source={StaticResource cvs2}}&quot;
              IsCrossSlideEnabled=&quot;True&quot;&gt;
    &lt;!--
        Main content template
    --&gt;
    &lt;GridView.ItemTemplate&gt;
        &lt;--
           Data template used to display the data
        --&gt;
        &lt;DataTemplate&gt;
            &lt;StackPanel Orientation=&quot;Horizontal&quot;
                Margin=&quot;12,10,0,0&quot;
                HorizontalAlignment=&quot;Left&quot;&gt;
                &lt;Image Source=&quot;{Binding Image}&quot;
                       Height=&quot;60&quot;
                       Width=&quot;60&quot;
                       VerticalAlignment=&quot;Center&quot;
                       Margin=&quot;0,0,10,0&quot; /&gt;
                &lt;TextBlock TextWrapping=&quot;Wrap&quot;
                           Style=&quot;{StaticResource ItemTitleStyle}&quot;
                           Width=&quot;240&quot;
                           VerticalAlignment=&quot;Center&quot;
                           Text=&quot;{Binding Title}&quot;
                           HorizontalAlignment=&quot;Left&quot;
                           FontFamily=&quot;{StaticResource SemiLightContentFontFamily}&quot; /&gt;
             &lt;/StackPanel&gt;
        &lt;/DataTemplate&gt;
    &lt;/GridView.ItemTemplate&gt;
    &lt;!--Group Style this will allow for the grouping visual effects that we want--&gt;
    &lt;GridView.GroupStyle&gt;
        &lt;GroupStyle&gt;
        &lt;!--Group Style Header template defines what controls we use in the header--&gt;
        &lt;GroupStyle.HeaderTemplate&gt;
            &lt;DataTemplate&gt;
                &lt;TextBlock Text=&#039;{Binding Name}&#039;
                           Foreground=&quot;{StaticResource PageForegroundBrush}&quot;
                           Margin=&quot;0,0,36,0&quot;
                           FontSize=&quot;{StaticResource HeaderLargeFontSize}&quot;
                           FontFamily=&quot;{StaticResource SemiBoldContentFontFamily}&quot; /&gt;
            &lt;/DataTemplate&gt;
        &lt;/GroupStyle.HeaderTemplate&gt;
        &lt;!--Group Style Container Style --&gt;
        &lt;GroupStyle.ContainerStyle&gt;
            &lt;Style TargetType=&quot;GroupItem&quot;&gt;
            &lt;Setter Property=&quot;Template&quot;&gt;
                &lt;Setter.Value&gt;
                    &lt;ControlTemplate TargetType=&quot;GroupItem&quot;&gt;
                    &lt;!--Change the orientation of the panel to change where the Group Header is positioned --&gt;
                        &lt;StackPanel Orientation=&quot;Horizontal&quot;&gt;
                            &lt;ContentPresenter Content=&quot;{TemplateBinding Content}&quot; /&gt;
                            &lt;ItemsControl x:Name=&quot;ItemsControl&quot;
                                          ItemsSource=&quot;{Binding GroupItems}&quot; /&gt;
                        &lt;/StackPanel&gt;
                    &lt;/ControlTemplate&gt;
                &lt;/Setter.Value&gt;
            &lt;/Setter&gt;
        &lt;/Style&gt;
        &lt;/GroupStyle.ContainerStyle&gt;
        &lt;GroupStyle.Panel&gt;
            &lt;ItemsPanelTemplate&gt;
            &lt;!--
                Provides a grid-style layout panel where each tile/cell can be variable size based on content.
            --&gt;
            &lt;VariableSizedWrapGrid Orientation=&quot;Vertical&quot;
                                   MaximumRowsOrColumns=&quot;6&quot; /&gt;
            &lt;/ItemsPanelTemplate&gt;
        &lt;/GroupStyle.Panel&gt;
        &lt;/GroupStyle&gt;
    &lt;/GridView.GroupStyle&gt;
        &lt;GridView.ItemsPanel&gt;
            &lt;ItemsPanelTemplate&gt;
                &lt;!--VirtualizingStackPanel VirtualizationMode=&quot;Recycling&quot; --&gt;
                &lt;StackPanel Orientation=&quot;Horizontal&quot; /&gt;
                &lt;/ItemsPanelTemplate&gt;
            &lt;/GridView.ItemsPanel&gt;
                    &lt;Button Visibility=&quot;Collapsed&quot; /&gt;
        &lt;/GridView&gt;
    &lt;/JumpViewer.ContentView&gt;
&lt;/JumpViewer&gt;
</pre>
<p><a href="http://blogs.xamlninja.com/wp-content/uploads/2011/09/JumpViewerContent.png" rel="shadowbox[sbpost-740];player=img;"><img src="http://blogs.xamlninja.com/wp-content/uploads/2011/09/JumpViewerContent-1024x575.png" alt="" title="JumpViewerContent" width="700" height="375" class="alignleft size-large wp-image-745" /></a></p>
<p>&nbsp;<br />
As you can see the Content section of the Jump Viewer comprises another control, in this case a Grid View, which provides the horizontal scrolling experience. A new feature for Metro is the ability to apply a Group Style on both the List and Grid View controls which provide the ability to group the data if your data model supports it. I will go into more detail about Group Styles in a future post. For now what we should understand is that when providing a Group Style we need to ensure that we provide a data template that will visualise the data in the header template and we can change the orientation of the layout by changing the Stack Panel in the Item Container Style from Vertical to Horizontal. </p>
<p>The Grid View also needs a data template for the items and there is also another new layout control called the Variable Sized Wrap Grid which is being used to layout the items in the Grid View. Once again I am loving this new layout and I will talk in more detail about the control in a future post. The most important thing for now is to understand that like the Wrap Grid, we can change the orientation and the Maximum Rows Or Columns properties which effect the layout of the items in the Grid. Sweet!</p>
<p>You may have also noticed that I have commented out the Virtualizing Stack Panel, I had problems when I used this, not sure why this is and when I find out more details I will update the post.</p>
<p>Enjoy!</p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.xamlninja.com/xaml/metro-controls-jump-viewer/feed</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>WP7Contrib &#8211; Bing Service Wrapper Part IV Location Simplified</title>
		<link>http://blogs.xamlninja.com/wp7/wp7contrib-bing-service-wrapper-part-iv-location-simplified</link>
		<comments>http://blogs.xamlninja.com/wp7/wp7contrib-bing-service-wrapper-part-iv-location-simplified#comments</comments>
		<pubDate>Tue, 23 Aug 2011 13:23:07 +0000</pubDate>
		<dc:creator>rich</dc:creator>
				<category><![CDATA[Bing Services]]></category>
		<category><![CDATA[WP7]]></category>
		<category><![CDATA[WP7Contrib]]></category>
		<category><![CDATA[WP7Dev]]></category>
		<category><![CDATA[Xaml]]></category>

		<guid isPermaLink="false">http://blogs.xamlninja.com/?p=634</guid>
		<description><![CDATA[Based on feedback around my first post in this series of talking about how to use Location I thought that I would revisit how you can use this really cool bit of stuff in your app. When I first wrote the original post it was much more bare bones however, there were lots of unanswered [...]]]></description>
			<content:encoded><![CDATA[<p>Based on feedback around my first post in this series of talking about how to use Location I thought that I would revisit how you can use this really cool bit of stuff in your app. When I first wrote the original post it was much more bare bones however, there were lots of unanswered questions when I did and could be taken out of context. Therefore I wanted to reiterate how easy it is for you app to incorporate Geo Location features and enhance the User Experience.</p>
<p>So, lets start off with some new code and how you can pretty much copy and paste this boiler plate code into your app and start to take advantage of Geo Location. <a href="http://awkwardcoder.blogspot.com/" target="_blank">Ollie </a>has done some refactoring of the defined constructors making the implementation simpler. Which means; if you are not using Dependency Injection; or MVVM; or just want something very specific from the service, these new constructors will give you the ability to do just that.</p>
<p>The code below can be found in the BingMapsLocationDemo folder under spikes of the WP7C along with lots of other samples including the original code that exercises the Bing Maps Wrapper.</p>
<p>First, we need an instance of the BingMapsService.</p>
<pre class="brush: csharp">
this.bingMapsService =
    new BingMapsService(&quot;Your credentials id&quot;, &quot;Your app id&quot;);
</pre>
<p>Next, we need to use our good friend the CriterionFactory that will do all the work required to generate the request that will be sent to the endpoint. There are a couple of flavours for Location, depending on what you want to do; for finding out the address of a GeoCoordinate you can use CreateLocationSearchForPoint; or for finding out the full address from a partial one you can use CreateLocationSearchForAddress.</p>
<pre class="brush: csharp">
var criterion =
    CriterionFactory.CreateLocationSearchForAddress(this.postCode.Text);
</pre>
<p>Finally, we need use Rx to perform the async call. Using the instance of the BingMapsService we call the  method which in our case is SearchForLocationUsingAddress that takes the criterion created by the factory as a parameter. </p>
<pre class="brush: csharp">
this.bingMapsService.SearchForLocationUsingAddress(criterion)
        .ObserveOnDispatcher()
        .Subscribe(result =&gt;
        {
         this.address.Text = result.Locations[0].Address.Locality;
         this.address.Text += Environment.NewLine;
         this.address.Text += result.Locations[0].Address.PostalCode;
         this.address.Text += Environment.NewLine;
         this.address.Text += result.Locations[0].Address.AdminDistrict;
         this.address.Text += Environment.NewLine;
         this.address.Text += result.Locations[0].Address.CountryRegion;
        });
</pre>
<p>Boom! Your done!</p>
<p>Hopefully, second time round this post is clearer and a far more succinct illustration of how to use the Location in your app. We will also continue to add some new projects into the Spikes folder to illustrate the other condensed constructors for Search, Imagery and Routes.</p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.xamlninja.com/wp7/wp7contrib-bing-service-wrapper-part-iv-location-simplified/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<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>WP7Contrib &#8211; Page Transitions and Navigation Service</title>
		<link>http://blogs.xamlninja.com/blend/wp7contrib-page-transitions-and-navigation-service</link>
		<comments>http://blogs.xamlninja.com/blend/wp7contrib-page-transitions-and-navigation-service#comments</comments>
		<pubDate>Mon, 21 Mar 2011 15:33:27 +0000</pubDate>
		<dc:creator>rich</dc:creator>
				<category><![CDATA[Blend]]></category>
		<category><![CDATA[WP7]]></category>
		<category><![CDATA[WP7Contrib]]></category>
		<category><![CDATA[Xaml]]></category>

		<guid isPermaLink="false">http://blogs.xamlninja.com/?p=433</guid>
		<description><![CDATA[I finally got around to updating the page transistions in wp7 contrib last week, its something that has been on my list for awhile. For a complete sample project check out the sample in the spikes folder where you can also find lots of other samples illustrating other tennants of the contrib. The transitions used [...]]]></description>
			<content:encoded><![CDATA[<p>I finally got around to updating the page transistions in <a href="http://wp7contrib.codeplex.com/">wp7 contrib</a> last week, its something that has been on my list for awhile. For a complete sample project check out the sample in the spikes folder where you can also find lots of other samples illustrating other tennants of the contrib.</p>
<p>The transitions used in the <a href="http://wp7contrib.codeplex.com/">WP7C </a>are based around the great work of <a href="http://blogs.claritycon.com/kevinmarshall/author/kmarshall/">Kevin Marshall</a> who originally created the <a href="http://blogs.claritycon.com/blog/2010/10/13/wp7-page-transitions-sample/">transitions</a>, we like them becuase they are lighter on memory usage and slightly faster when compared to the page transitions found in the WP7 toolkit. Now that is not too say I dislike the transitions in the toolkit, I actually really like them mainly because we have the ability to define these transitions in Xaml and hopefully there will be some future design-time support in Blend where we could run these transitions. Xaml support for the transitions is definately on the vNext list for the WP7C as we believe its important for designers to able to change, apply and understand the different transitions that are available.</p>
<p>When comparing implementation details, the toolkit uses a custom Frame called a Transition Frame; and WP7C does this at a page level all the pages in your app have to sub class the Animated Base Page. Other differences include; the toolkit uses a Render Transform and WP7C uses Composite Transform; the WP7C uses the XamlReader.Load to setup the storyboards, however the toolkit has specific loose Xaml files that contain the storyboards.</p>
<p>So the new page transitions includes the different Rotate permutations for your page transitions, I also added in some new slide and fade transitions. You can play with these and all the other different transitions by downloading the sample app.</p>
<p>The other thing that I decided to add into the app was a very simple implementation of the WP7C navigation service. Page transitions and navigation are interconnected, when you navigate to a page you want to execute a transition between the current page and the new page, this is approapiate when going forwards or backwards. Normally we would wire up the WP7C Navigation Service in the bootstrapper of our app and use a DI framework to new this up. In order to keep everything super simple I am using the interface and manually newing up an instance, also note that I am not using a View Model this is simply to show the flexibility of the WP7C Navigation Service.</p>
<pre class="brush: csharp">
private WP7Contrib.Services.Navigation.INavigationService navigationService;

public MainPage()
{
        InitializeComponent();

       AnimationContext = LayoutRoot;
       this.navigationService = new WP7Contrib.Services.Navigation.ApplicationFrameNavigationService(
                                   ((App)Application.Current).RootFrame);
}
</pre>
<p>Notice how we grab the RootFrame and pass this in to the constructor of the WP7C Navigation Service the same code can be used in a bootstrapper. When using the WP7C transitions there is no requirement for us to change the base class of the frame in the App&#8217;s Initalize Phone App handler like we would do when using the toolkit.</p>
<pre class="brush: csharp">
private void InitializePhoneApplication()
{
    if (this.phoneApplicationInitialized)
    {
        return;
    }

    // Create the frame but don&#039;t set it as RootVisual yet; this allows the splash
    // screen to remain active until the application is ready to render.
    this.RootFrame = new TransitionFrame();
    this.RootFrame.Navigated += this.CompleteInitializePhoneApplication;

    // Handle navigation failures
    this.RootFrame.NavigationFailed += RootFrame_NavigationFailed;

    // Ensure we don&#039;t initialize again
    this.phoneApplicationInitialized = true;
}
</pre>
<p>Instead we need to hang all our pages from the Animated Base Page, pay close attention to; the constructor where we assign the Animated Context of our base page to the LayoutRoot of our page; and the overridden Get Animation where we are deciding which transitions to fire based on the Animation Type.</p>
<pre class="brush: csharp">
namespace PageTransition
{
    using System;

    using WP7Contrib.View.Transitions.Animation;

    public partial class Slide : AnimatedBasePage
    {
        public Slide()
        {
            InitializeComponent();

            AnimationContext = LayoutRoot;
        }

        protected override AnimatorHelperBase GetAnimation(AnimationType animationType, Uri toOrFrom)
        {
            if (animationType == AnimationType.NavigateForwardOut)
            {
                return new SlideLeftFadeOutAnimator { RootElement = LayoutRoot };
            }

            if (animationType == AnimationType.NavigateBackwardOut)
            {
                return new SlideRightFadeOutAnimator { RootElement = LayoutRoot };
            }

            if (animationType == AnimationType.NavigateForwardIn)
            {
                return new SlideLeftFadeInAnimator { RootElement = LayoutRoot };
            }

            return new SlideRightFadeInAnimator { RootElement = this.LayoutRoot };};
        }
    }
}
</pre>
<p>For completeness I have covered off the different permutations of Navigating forward or backward. The implemented page transitions have a corresponding Animator which makes it straightforward to implement the type of animation that you require. And that is everything you need in order to get page transitions working in your app. Once you have implemented the transitions you want then its a fairly simple task of using the WP7C Navigation Service to navigate to a page in your app.</p>
<pre class="brush: csharp">
private void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (AnimationList.SelectedIndex != -1)
    {
        switch (AnimationList.SelectedIndex)
        {
            case 0:
                this.navigationService.Navigate(new Uri(&quot;/View/Turnstile.xaml&quot;, UriKind.Relative));
                break;

            case 1:
                this.navigationService.Navigate(new Uri(&quot;/View/TurnstileFeather.xaml&quot;, UriKind.Relative));
                break;

            case 2:
                this.navigationService.Navigate(new Uri(&quot;/View/Continuum.xaml&quot;, UriKind.Relative));
                break;

            case 3:
                //slide right
                this.navigationService.Navigate(new Uri(&quot;/View/SlideRight.xaml&quot;, UriKind.Relative));
                break;

        }
    }
}
</pre>
<p>And we are done!</p>
<p>Couple of things to watch out for when implementing the page transitions</p>
<ol>
<li>Make sure that you have the correct base url in you WMAppManifest.xml.<br />
It should look something like this</p>
<pre class="brush: xml">
&lt;Tasks&gt;
      &lt;DefaultTask  Name =&quot;_default&quot; NavigationPage=&quot;View/MainPage.xaml&quot;/&gt;
    &lt;/Tasks&gt;
</pre>
<p>Even if you have a sub folder which contains your Views
</li>
<li>If you have already overriden the OnBackKeyPress handler remember to call the base implementation</li>
</ol>
<p>If you have created transitions and happy to share or have ideas for ones you would like to see then please contact me.</p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.xamlninja.com/blend/wp7contrib-page-transitions-and-navigation-service/feed</wfw:commentRss>
		<slash:comments>3</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>PathListBox Adventures &#8211; radial layout</title>
		<link>http://blogs.xamlninja.com/silverlight/pathlistbox-adventures-radial-layout</link>
		<comments>http://blogs.xamlninja.com/silverlight/pathlistbox-adventures-radial-layout#comments</comments>
		<pubDate>Mon, 29 Mar 2010 11:13:45 +0000</pubDate>
		<dc:creator>rich</dc:creator>
				<category><![CDATA[Blend]]></category>
		<category><![CDATA[PathListBox]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[Xaml]]></category>

		<guid isPermaLink="false">http://blogs.xamlninja.com/?p=224</guid>
		<description><![CDATA[The PathListBox ROCKS, if you have not heard of this control before then checkout Christians blog for more details and also his session at mix 10. The PathListBox solves some of the tricky issues related to creating custom panels for a ListBox or ItemsControl. Previously when we need custom layout of visual elements inside of [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://blogs.xamlninja.com/wp-content/uploads/2010/03/RadialPanel.png" rel="shadowbox[sbpost-224];player=img;" target="_blank"><img style="margin: 5px auto; display: block; float: none; border-width: 0px;" title="RadialPanel" src="http://blogs.xamlninja.com/wp-content/uploads/2010/03/RadialPanel_thumb.png" border="0" alt="RadialPanel" width="632" height="484" /></a></p>
<p>The PathListBox ROCKS, if you have not heard of this control before then checkout <a href="http://electricbeach.org/" target="_blank">Christians</a> blog for more details and also his session at mix 10. The PathListBox solves some of the tricky issues related to creating custom panels for a ListBox or ItemsControl. Previously when we need custom layout of visual elements inside of these controls we would typically create a custom Panel and crank C# code and some positioning logic to layout the elements as we needed. However, with the introduction of the PathListBox we nolonger have to resort to building a panel and thus lowers the barrier to entry for designers who want to create custom layouts without having to be reliant on a developer to build the panel.</p>
<p>To get going with the PathListBox I wanted to create an simple Silverlight app which pulled back some results from digg, this is something which I have done in the past to illustrate the basics of MVVM in my session from PDC. While on the topic of MVVM its great to see that we now have an MVVM template inside of Blend that we can use. In this post I am not going to talk about the MVVM templates as I have only started out with them and so to give a comparison would not be justifiable at this stage, but I will posting an article when I have it straighten out in my head.</p>
<p>So for this first adventure I created a new MVVM Silverlight application and added a Model and a Service folder. As we already have the code for the digg service and the model created <em>I copied these classes and moved them into their respective folders in the project. Open up the VM that has been added into the project and we can see that it implements INPC. The other thing to notice is that the constructor in parameter less, which is unlike my VM’s where I would normally inject an interface. So for the purposes of this example i am going to new up the interface inside of the constructor.</em></p>
<p>Ok so there are 3 steps that we need to perform in order to recreate the radial panel visual layout that is illustrated above. First we need to create our path on the design surface and then add the PathListBox to the design surface and associate the path with the PathListBox. As with a regular ItemsControl or ListBox we need to bind it to a list of items which in this case is our collection of FeedItems. Blend 4 Beta does quite alot of work for free, you will notice it has created the DataTemplate, ItemContainerStyle and ItemPanelTemplate which is rather nice. So here we start our 3 Steps and each step is associated with the templates and style.</p>
<p>First select the DataTemplate of the PathListBox either from the crumb bar or from right clicking in the objects panel. What we need to do here is add a ChangePropertyAction which fires when we LeftMouseButtonDown on to the DataTemplate so that we can set a flag on the data bound object so that it gets removed from the current list and added to second list. Once we have added this we need to change the RotateTransform on the StackPanel to 90.</p>
<p><a href="http://blogs.xamlninja.com/wp-content/uploads/2010/03/PathListBoxDatatemplateChangePropertyAction.png" rel="shadowbox[sbpost-224];player=img;"><img style="margin: 5px; display: inline; float: none; border-width: 0px;" title="PathListBoxDatatemplateChangePropertyAction" src="http://blogs.xamlninja.com/wp-content/uploads/2010/03/PathListBoxDatatemplateChangePropertyAction_thumb.png" border="0" alt="PathListBoxDatatemplateChangePropertyAction" width="644" height="476" /></a></p>
<p>Navigate back to the PathListBox and this time we want to edit the orientation on the items on the path so that they are OrientToPath and check the Wrap Items checkbox.</p>
<p><a href="http://blogs.xamlninja.com/wp-content/uploads/2010/03/PathListBoxSettings.png" rel="shadowbox[sbpost-224];player=img;"><img style="display: inline; border-width: 0px;" title="PathListBoxSettings" src="http://blogs.xamlninja.com/wp-content/uploads/2010/03/PathListBoxSettings_thumb.png" border="0" alt="PathListBoxSettings" width="584" height="484" /></a></p>
<p>The second step is to move into our ItemContainerStyle for the PathListBox and change the VSM states so that we have a nice transition for the items when they are loaded and unloaded. With the release of Blend 4 Beta a new set of states have been added to the ListBoxItem. PathListBoxItem subclasses ListBoxItem and so we have the ability to modify the transitions for the BeforeLoaded and AfterLoaded states. For these I</p>
<p><a href="http://blogs.xamlninja.com/wp-content/uploads/2010/03/PathListBoxStyleLayoutStates.png" rel="shadowbox[sbpost-224];player=img;"><img style="margin: 5px; display: inline; border-width: 0px;" title="PathListBoxStyleLayoutStates" src="http://blogs.xamlninja.com/wp-content/uploads/2010/03/PathListBoxStyleLayoutStates_thumb.png" border="0" alt="PathListBoxStyleLayoutStates" width="440" height="154" align="left" /></a></p>
<p>simply changed the Opacity on the root element so that we can have a simple fade in type transition. Next we need to change the length of the transition in this case to 0.3 seconds, and change the easing function to your desired choice. The other changes I made here was to enable the Fluid Layout and turned on the design time layout transitions so that you can see your transitions during design time. Navigate back to the PathListBox.</p>
<p>The final piece to the puzzle is to change the ItemPanelTemplate. Edit the template either via the assets panel or the crumb bar. Here we are looking to add  the FluidMoveBehavior on to our PathPanel which will be responsible for providing the animation effect for moving items between the two PathListBox’s.</p>
<p><a href="http://blogs.xamlninja.com/wp-content/uploads/2010/03/PathListBoxItemsPanelTemplateFluidMoveBehavior.png" rel="shadowbox[sbpost-224];player=img;"><img style="margin: 5px auto; display: block; float: none; border-width: 0px;" title="PathListBoxItemsPanelTemplateFluidMoveBehavior" src="http://blogs.xamlninja.com/wp-content/uploads/2010/03/PathListBoxItemsPanelTemplateFluidMoveBehavior_thumb.png" border="0" alt="PathListBoxItemsPanelTemplateFluidMoveBehavior" width="644" height="446" /></a> The important things to note here include; we have selected the Children option from the AppliesTo dropdown as we want this particular FluidMoveBehavior to effect all the items in the ListBox; I changed the duration and also the easing functions that I wanted to use; I also selected the DataContext option from the Tag dropdown as I want to capture the data object associated with the item that is being animated. Navigate back to the PathListBox……</p>
<p>And we are done.</p>
<p>3 simple steps for you to add a radial panel layout into your project.</p>
<ol>
<li>Change the data template so that it can handle a user interaction</li>
<li>Change the ItemContainerStyle BeforeLoaded and AfterLoaded States</li>
<li>Change the ItemPanelTemplate by adding in the FluidMoveBehavior</li>
</ol>
<p>We also used ChangePropertyAction to manipulate the data in our collections exposed by the VM, and  we  used the FluidMoveBehavior to animate selected items from one PathListBox to another. The ability to do this without having to write any C# is a great step forwards, it does have some consequences but the advantages from my prospective outweigh the disadvantages.</p>
<p>The next thing that I want to do is animate each individual PathListBoxItem depending on where they are on the Path associated with the PathListBox.</p>
<p>All the code for this example you can find on my SkyDrive Folder.</p>
<p>&lt;iframe title =&#8221;Preview&#8221; scrolling=&#8221;no&#8221; marginheight=&#8221;0&#8243; marginwidth=&#8221;0&#8243; frameborder=&#8221;0&#8243; style=&#8221;width:98px;height:115px;padding:0;background-color:#fcfcfc;&#8221; src=&#8221;http://cid-118ee1873690fc1d.skydrive.live.com/embedicon.aspx/Silverlight4/MvvmApplication3.zip&#8221;&gt;&lt;/iframe&gt;</p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.xamlninja.com/silverlight/pathlistbox-adventures-radial-layout/feed</wfw:commentRss>
		<slash:comments>8</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>

