PathListBox Adventures – radial layout

RadialPanel

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 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.

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.

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 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.

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.

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.

PathListBoxDatatemplateChangePropertyAction

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.

PathListBoxSettings

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

PathListBoxStyleLayoutStates

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.

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.

PathListBoxItemsPanelTemplateFluidMoveBehavior 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……

And we are done.

3 simple steps for you to add a radial panel layout into your project.

  1. Change the data template so that it can handle a user interaction
  2. Change the ItemContainerStyle BeforeLoaded and AfterLoaded States
  3. Change the ItemPanelTemplate by adding in the FluidMoveBehavior

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.

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.

All the code for this example you can find on my SkyDrive Folder.

<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/Silverlight4/MvvmApplication3.zip”></iframe>

Its a POC don’t worry about the data…

In the last post my aim was to start a conversation around the advantages of building a visual data model.

But this is a POC ? Why would you do this?

Well its an interesting question and I am sure that there are folks out there who like to build prototypes and POC’s in this way, but based on my experience this usually ends up taking longer as you find yourself adding a workaround to the existing workarounds resulting in friction between what you want to do and the limitations of the framework. So the approach that I prefer to use is to take some time out at the start of the process and deconstruct the visual designs and build out a data model to represent what information needs to be presented. We can then go off and create the simple factory classes to build these data structures and take full advantage of the features supported by the framework. In essence we are using the same techniques that we would use for a production quality application but slimming down a journey through the application using more appropriate patterns.

This simple process is not time consuming, helps clear up any potential misunderstanding of how the application will react based on certain interactions, and it means that when deconstructing the visual designs its easy to figure out what type of control you can use in order to build the visual and if the control you are thinking about using will support the interactions required. The additional bonus here is that if you want to go a step further then you easily wire in a simple MVVM pattern, again this is something that I do however its not an essential step.

What I also like about this approach is that POC’s are usually built in a short timeframe and are thus open to change on a regular basis and we need to have an approach which reduces churn. By having a good data model you can limit the pain when things change as you can easily change the data object to suit and then a simple change to the Xaml. The opposite of this can result in lots of conditional logic which becomes prone to bugs and also limiting the application to potentially just a clickable mockup.

The other benefit which results in this approach is the level of reusability that I can pull from the POC and move into the production application. By having taken the time to produce a data structure that is usable this means that I can potentially reuse all the existing data templates, data bindings, styles, templates and certain custom controls. Again from my experience this level of reusability is normally higher than when we push forwards with a more static and tightly coupled approach.

To put this into a better context, a number of Surface applications that I have been involved in recently have required a ScatterView with ScatterView Items as these control provide those all important gestures for NUI interactions out of the box. Cool, but we are faced with the options either; create a known number of items and potentially recreate the same style but with different hardwired data; or create a single data template and style and take advantage of the data bind features. This can easily be achieved by data binding to the DP’s provided by the ScatterView Item that controls its placement, its easy to maintain and manage when those known changes happen. It also provides us with the flexibility to extend certain aspects rapidly without getting freaked out by the amount of conditional logic being added to the app.

My approach here is a simple one, create a base class for all your data controlled visuals which allow you to provide point data information so that when the objects are created you can initialise them where they need to be placed on screen. You can also add into here some more properties such as Orientation and data bind your data object property to the Orientation DP. Properties such as CanScale etc I would manipulate in a Style for the ScatterView Item, however there is no reason why you could not add them into the base. My reasons for the using a Style is so that when I am working with the designer I can easily make changes to the Style when we are both using Blend, it also allows me to share the work with designers visually, this for me is essential, personally I am more of a visual guy I prefer to see something rather than read textual content a visual helps paint the picture in a more accurate way with less room for individual perceptions of a textual instruction or description.

This simple approach provides; the ability to place visual elements exactly where the designer wants them;animations can be built in order to animate these visual elements on and off screen, interrogating the strongly typed data types means that we can apply the required styles on demand; reduces the complexity of app by taking advantage of data binding.

Just to break this down a little further, with the Tag Heuer implementation, I created a bunch of data objects for the locations around the world, London, Los Angeles, Cape Town, Sydney etc; all of which subclass the same base called Location. Location, Travel and Watches, the three different states of the app all subclass a class providing the positioning logic which intern subclasses an abstract base implementing INPC. I then have a data templates for each of the locations that we need to visualise, London, Los Angeles, Cape Town, Sydney etc. The data templates deal nicely with presenting our data, however there is a problem with layout as some of the aforementioned locations need to be positioned from left to right and some need to be positioned from right to left. To achieve this visual effect I used a different style
one for left to right and a second for right to left and wired these into the data template. I could have written c# to flip the visual tree however in this instance it was more effective to rebuild the styles in Blend it also has the advantage that I can show the designer in Blend the visual created and make any additional tweaks required.

Illustrated_Travel

I used the same technique for the F1 GP races and the watches area all of which have strongly typed data objects to encapsulate the visual information providing me with the advantages mentioned above to create and adapt quickly with the changes to the visual designs, it also allows me to take advantage of OO when it comes to adding additional properties to the base classes which will have a ripple effect down the object hierarchy.

In your next POC or prototype in WPF I hope that you will feel confident enough to try out this technique and reap the benefits that are at your disposal. Unfortunately the current version of Silverlight does not support implicit data templates, which in my humble opinion is a fundamental missing part of the Silverlight framework. Hopefully we will see this in a future release.

In the next post I am going to dig into how I built the watches section of the application and also dive into how interactions with the watch chrome and its content were created.

JC Decaux and Tag Heuer Surface Application deployed to Heathrow T5

T5_2 surface_unit_photos_manemailable

This is really the start of a number of posts that I have been meaning to put together for a while now. These are centred around how to rapidly build prototypes. It’s a technique that I use on a regular basis both for WPF and for Silverlight. In order for me to get across how effective this is it seems only right to provide context of how you can also take advantage of this technique.

More about that later, for this particular implementation I partnered with Splendid in order to produce an interactive experience for travellers at London Heathrow T5 lounges. The brief was to help raise brand awareness of the new Tag Heuer watches available and take advantage of the collaborate aspects provided by Surface.

The Tag Heuer Surface application has three main areas of functionality, all driven by the concept of time.

04_travel_detail1

Travel Guide: The application displays the current time at your departure destination, displayed on a Tag Heuer watch display with moving hands. Using a stylized world map passengers can choose popular destinations and explore local time, travel duration and view local landmarks.

06_sports_detail

Sports Finder: Tag Heuer have a number of sports stars as ambassadors, we chose Lewis Hamilton as the trial location was the UK. Passengers can explore the world find the next Grand Prix including a  countdown and images of last years race.

09_collection_detail1_resizeWatch Explorer: A Tag Heuer Application wouldn’t be quite right without the ability to explore their classic  watch collection, passengers can use gesture to explore high-res images of the men’s and women’s collections with the ability to sign-up for an email on your favourite watch. The email contains details of the watch and your nearest location to purchase.

For a UX developer there are some really rather cool interactions used in each of the areas. I am going to try and give a higher level overview of these areas  below and then jump into the detail in separate posts. The first of these are interactions present in each of the different functional pillars of the experience illustrated above and were designed so that visual elements could be placed into specific areas, animation of these items on and off screen and designed in such away that data bound objects provided the visual positioning information. The solution I used here was a combination of strongly typed data templates with model objects that contained the required coordinates of where to be positioned on screen and styles to create the required interactions.

When deconstructing the visual design I knew that the ScatterView Control would do the job nicely and having the coordinates in the model meant that we can take full advantage of data binding as each ScatterView Item has a centre and orientation DP which can be used to achieve this layout. Using a different ScatterViewItem Style provided the ability to choose different interactions and visuals based on which area of functionality is in use. Note there are 2 styles for the map points; a style for map points which are right aligned and a style for those which are left aligned. Using the strongly typed data templates and the use of data binding provides a clean and easy to achieve solution that provided the required interactions. The application was aware of its state and by changing the data based on state the usage of the strongly typed data templates come into their own as these state changes are triggered resulting in the new visuals to be displayed all done using data and data bindings in the Xaml.

For the travel section animated clocks were used and the TimeZoneInfo class provided the ability  to calculate the time in different time zones. Here I used a dispatch timer that was ticking away and then updating the value of the data object. Each of the different time zones were associated data objects of the current location using data binding and INPC meant that we can change the time in the data object and this will trigger the animations used to rotate the hands on the watch.

The watch section has cool interaction where there is a 2 level zoom mechanism, I broke this one down to09_collection_detail1_resize be a ScatterViewItem which wraps a ScatterView. This allowed for an interaction which meant the user could  use a pinch gesture in increase the size of the outer ring and then a second pinch gesture can be used to manipulate the watch being displayed. What I like about this interaction design is that it allows the user to easy move and collaborate with other users interested in seeing the detailing of the watch. More importantly this also meant that I could take full advantage of data binding and strongly typed data templates.

As you may have noticed there is an underlying theme happening here, data and Xaml. For me WPF is really all about your data, get the data structure right that needs to be presented on screen and we can take full advantage of the framework and reduce the amount of C# code we write to a minimum.

links

The Moodie Report http://www.moodiereport.com/document.php?c_id=1113&doc_id=23335

Resource Dictionaries

In this post I thought that it would be interesting to share some of my thoughts that I have been having recently around Resource Dictionaries (RD) and how they are structured. It is very easy to just put everything into your generic.Xaml or even into your app.Xaml files and let the designer run away with implementing their designs, but this is not too say that its the best way to roll.

From a developer prospective these files can become large very quickly and the result is a complete management headache when it comes to maintaining the styles, control and data templates. Its is also rather easy  to allow this to happen as its in the Xaml and its what the designer produces, in effect its someone else’s responsibility. What is rather interesting and confusing at the same time is that Blend actually works very well when it comes to dealing with resources that are all in one file and it provides the designer with an easy way manage styles and templates. The other interesting thing about RD is that its actually at the heart of the Designer and Developer collaboration, its one of the areas where these two worlds collide. Therefore one of the ways in which we can help improve the workflow is to have a better understanding of RD and create some guidelines on how to best go about structuring them.

Unfortunately, even though RD are one of the core parts that make up the presentation layer there is very little information on best practices on how we should be doing this and why its important to get it right in order from which to have a good platform to move off from. Structuring RD in the wrong way can have rather serious performance problems.

There is a great article on the WPF Disciples pages providing very good advice on how to structure your RD and naming conventions, but I want to attempt to take it a little further. There are a number of different scenarios that I have come across and I am sure that there will be more along the way.  These include; a POC application where this is built quickly and iteratively and requires a compelling UI but there is a high potential the application will not make it into production; themeable applications where a number of different themes can be applied to change the look and feel; and also applications that leverage 3rd party controls which have their own and sometimes rather interesting ways of how they are styled and templated. Each scenario is different but can be solved in the same way by using well structured RD to produce a clean, performant and easy to maintain application.

Ok, so how can we achieve a better structuring of the RD, help improve collaboration and provide a basic pattern and best practices in order to satisfy the different scenarios outlined above ?

Putting your RD in a separate project is the first thing to do, there are a number of advantages in doing this; but primarily this is about separation of concerns to help with workflow; and it helps to provide a blue print of a theme that can be reused over time.

In addition to the guidelines put forwards from the WPF list I am also going to add some more into the mix.

Suggested WPF Disciples Resources :-

BrushResources – solid brushes, linear gradient brushes and drawing brushes

ConverterResources – allows us to reference any of the converters by merging our resource dictionary with this file, rather than re-declaring our converters every time.

ImageResources – as above, allows us to declare an ImageSource once and reference it from anywhere. 

TextResources -styles applied to textual elements (Hyperlinks, TextBlocks, etc.)

Additional Resources:-

Colours – for simple colours used as a swash for branding of clients colour palette.

DataTemplates – holds all the Data Templates used in the application.

Storyboards – holds all the Storyboard animations.

VectorGraphics – holds all the vectors graphics

CustomControls – holds styles and templates for those custom lookless controls

CommonControls- holds styles and templates for those common controls

Now the above list is not an exhaustive one and there is a high potential that this may change in the future but for now these provide a good platform from which to start. There are a number of ways in which you can slice and dice the RD used in your application some of which I will talk about shortly, but in general its best to think about the RD as a whole. The reason for this is that its best to see the Xaml assets as what constitutes your design and interaction of the UI that you are projecting onto the view for the user to experience. Therefore a change in the template or style means a  complete new design. By thinking about them in a more holistic view as a the sum of all parts.

Therefore by splitting up the styles, templates etc into different high level RD categories provides the capabilities for the designers to work in an independent way and not have the constraints of working in the same project as the developers. The majority of times you will want to split out the RD into a separate project, and provide an area where they can create and design controls and elements. It also means that as they are working in a separate project they are completely separated from the developers but they are both working in the same solution.

What are those other views of RD that I mentioned earlier. Another potential way of looking at splitting up the RD is to break out the control templates and styles and place those into separate files. This will provide the ability to change the colours, font types etc and leave the control templates alone, which is great for those situations where you want to restyle the application and want to retain the layout of the controls. However, there are some problems with this approach; making significant changes to the style of controls will almost certainly mean that you will have to change the layout of the control, or building a custom control to handle the different styles; support in Blend for this type of structure is sub optimal in that it becomes more difficult to navigate and manage the styles and templates.

So why is it important to structure the RD in this way ? Why can they live all in the same Generic.Xaml file ? Is it the developer or the designer who owns the files ? How does this make my application more themeable ?

So those are a few of the questions which I have been asked about recently from both designers and developers, and they are all good questions and ones which i have also been thinking about hence my solution attempts to tackle these questions and provide a simpler implementation of how to use RD in your app.

One of the main problems with coming up with a good structure is the lack of guidance that is actually out there, plenty of high level information around some structure and naming conventions but no real information on the details. Rather frustratingly although we have gone head first into solving and building frameworks that address MVVM and come up with some notable solutions. It does feels like we have neglected an important area of the presentation layer.

What is rather interesting is how differently developers and designers perceive RD and this comes out in how they implement them in the app.

Developer : As a developer it is a natural and in the interest of best practices to split out each individual control so that each control is sat in its own RD.

Designer: As a designer its natural to think of all the controls at a higher level so that at set of individual controls contribute to the overall design of the app.

So as you can see neither side is right or wrong its their interpretation of RD which differs and this is natural as the different roles have different views and priorities on what is required to build the User Experience. What is interesting as well is that these opinions are skewed by the tools that they use and how they interpret and solve problems. The developer is very much focused on detail and implementation, mean while the designer is more interested in the higher level and the total experience of their design.

Therefore a combination of both these views seems to feel right where we split up the RD into a higher level categorisation with good naming conventions. This approach meets both parties needs and is Blendable allowing the designer to work in an environment which has a reduced reliance on the developer world and vice versa.

So I am hoping this that has made you think a little more about RD. In the next post I am going to talk more about how to implement the RD in your application and drill into the performance issues related to implementing RD and some sample code to help with guidance.

PDC09 – Meet the Griffs Code drop

Ian and myself really enjoyed presenting our pre conference session  “Getting the most out of Silverlight” and we both hope that you enjoyed the sessions. The slide decks will be posted at some point by the event team and I will update the post when this happens so that you can get copies of the decks.

As promised I have stashed all the final code examples up on my skydrive folder so that you can download and play with the samples. As we ran out of time in the last session what I will do in the next week or so is to record a Camtasia session and capture what I unfortunately did not get time to go over during the session.

I have named the zip files as intuitively as possible so these line up with the title of the session.

What I also wanted to briefly mention is that in the MEF and Ninject demos you will see that I am using Commands from the Silverlight Extensions project on CodePlex. The command pattern that is used here is a standard command pattern common to WPF. In the current release there is no support for Commands so what you will see included in the projects are the Command classes that I need in order to harness the power of Commands.

In a previous life I wrote a post on WPF commands that you may want to take a look at if you are not familiar to the Command pattern used in WPF and how it helps to separate out UI logic into you View Model and helps increase the testability of your code that responds to the behaviours in your application. The refactor that I did here was to remove the click event handler on the button and replace this with a command. There are 3 steps for refactoring out the event handler.

First we need to create a commands.cs file and create a Commands class which will hold all our commands associated with our view model. In essence we are going to be providing a list of possible actions that the View Model can perform in relation to the view. Once we have created the class we need to define our commands that we want which in our demo is called RefreshFeedItems then we need to add in public mechanism so that we can invoke the command from the view so that it can be wired up to a button.


using StandardViewModel.SLExtensions.Input;

public class Commands
{
      private static readonly Command refreshFeeds = new Command(RefreshFeedItems);

      public static Command RefreshFeedItems

      { get { return refreshFeeds; } } }

Now that we have defined the command that we want to fire we need to do the second part which is to wire up the command in the Xaml of the view.

     Input:CommandService.Command=RefreshFeedItems

     <Button Content=Refresh
                    Grid.Column=2
                    Margin="3,3,3,3"
                    IsEnabled="{Binding IsRefreshEnabled}"
                    Input:CommandService.Command="RefreshFeedItems" />

We can now remove the click handler code behind of the view.

The finally part is to implement the CanExecute and Executed code in the ViewModel, so move into the Constructor of the ViewModel and here wire up the commands.

       Commands.RefreshFeedItems.CanExecute += (sender, args) args.CanExecute = true;
       Commands.RefreshFeedItems.Executed += delegate(object sender, ExecutedEventArgs args)
         {
                        Refresh();
         };

And we are done. Enjoy. One thing to note is that there are other types of commands, RelayCommand and DelegateCommand which are also very cool black belt ninja moves for dealing with separation when building your MVVM apps

Using contextual design time data with SketchFlow

Design time data can be used to provide contextual data for your sketches and prototypes when demonstrating these ideas to your clients.  I want to highlight some of the areas that I am leveraging today that have helped to speed up the process of creating prototypes and my interaction with User Experience and Visual designers.

WelcomBackScreen My aim was to build a simple prototype using design time data in the prototype in order to provide a more contextually rich prototype for the user to interact with. This can be done alongside the sketches which the User Experience person is putting together or later once you have drilled  down to a couple of sketches which your client want to move into a prototype phase. From a developer prospective getting to know what data you have available and the ability to communicate with the UX on how this can be visualise early on in the process I have found to be invaluable.

So the prototype that I want to attempt is a simple shopping cart style application that communicates to the client what we are thinking about with regards to a User Journey which illustrates; how users will login into the application; a filtered list of products which meet previous buying habits; the ability to the user purchase items; and a page to show the checkout of those items. There is also a design element which means that the user has a personalised greeting on each of the pages.

To create each of the screens is trivial, in the sketchflow flow document window right click and add your screens give them the right names and link the screens together to illustrate the flow for the user journey. Next take the sketches from the UE and import them into Blend, luckily for me the designs are in a psd format so I can easily import these into Blend and get up and running, if this is not there are other supported formats which can be imported easily. Once we have the screens in place and sketches imported the next step is to add navigation behaviours so that when the prototype runs in the player our client can interact with the prototype and follow the journey.DesignTimeDataDataTab
As we are not intending on writing any logic at all and adding the design time data support is something we want to do in the lightest possible way our goal is to communicate the flow of the application and the journey the user will follow when interacting rather than logic and branding. The prototype at this stage is really to uncover the functionality and highlight where the complexity may be when implementing that logic, in order for us to communicate with the client potential areas of functionality which are going to be expensive to build in order for the client to assess the ROI of the features to be built in our initial brief. Therefore, we should not be including design elements at this stage or anything that lets our client get distracted from the journey and proposed experience that we want to take the user on when performing this particular task. For me, design elements come later when we have done a couple of iterations and have decided on the idea which we are going to take into production.
My intentions were to create a collection for the shopping basket and get this to contain a custom data type of productitem however when I attempted to do this blend does not recompile the .cs file correctly and thus I get an error in the design time data Xaml.

How does the design time data work?

When you are creating deign time data from the Blend menu, Blend is kindly generating the code behind to support your data structures that you are specifying for your prototype. The Xaml file produced is where you data that populate the code behind lives. The xsd is the mapping of the types and their definition. The xsd is an auto generated from the .cs file which Blend creates.

Unfortunately in the current release there is no support for copying and pasting data, so there is no support for creating a collection and then copying these contents to another collection, this is also the case for copying and pasting complex objects around your data source. The scenario why it would be good to have this functionality can be seen in our sample prototype, we have a list of products and we want to add the products collection to our shopping basket collection, therefore the ability to copy our predefined data into our new collection would be very helpful. Especially when we take into consideration that both collections are of the same type. So what choices do we have, well from what I can find there seems to be 2 options; BuyScreenfirst re adding the items using the Blend UI; or roll up your sleeves and edit the cs manually. If you are nervous about cs then option 1 is the right way.
One of the reasons why this functionality does not seem to be present in Blend is that there is a certain level of heuristics involved where Blend has to interpret what we mean and this in itself could become a nontrivial piece of functionality however, it is still possible and I hope to see this functionality in the next release (fingers crossed).

  1. If you want to change the cs file here are the steps :-
    1. First create the design time data structure that is required for the products collection, next create your Shopping basket collection.
    2. Save and build the project.
    3. Open up the .cs file and in here you will find the classes for the product and the product collection classes, you will also find the new definitions for the shopping basket collection and the items contained in that collection.
    4. Remove the shopping basket item class and modify the collection so that it contains a type of product item class.
    5. Save the project and build. You should get a compilation error in the Xaml file as the ShoppingBasket Item class is no longer defined.
    6. Open up the Xaml file and copy the product items from the product collection and paste them into the shopping basket collection.
    7. Save and build the project and you should have a successful build. We can then bind the shopping basket to the shopping basket user control.

So although there is some manual work to do its rather trivial hence the reason why i think this process could be automated.

Once again the power of design time data can be harnessed to provide a richer experience for your prototype, it is however important to only start doing these tasks at the right iteration, and at the moment this is normally around when you have started to dig into a reduced set of ideas that could be used to move into a prototype and its at this iteration where analysis of the datasets needs to be cleared up and an understanding of what data needs to be presented to the UI in order to provide a rich User Experience.
Using data templates to present the data means that we can layout and display contextual data for those parts of the user journey, Blend support for GUI editing of data templates when used in itemscontrols provides a quick and graphical mechanism for editing the layout. Its also the creation of these styles and templates later on in the final stages of the prototyping have potential high levels of reusability when moving into build the clients POC, what is interesting is that around this stage you are more than likely to be building visuals for the POC. Designers assets produced as vector graphics, adobe illustrator and Photoshop files can be imported into Blend in order to create styles and templates in order to recreate the visual design. Those datatemplates which were built in the earlier iterations can be reused with new Styles and Control templates providing you with the ability to speed up the entire process and potentially create a higher number of prototypes that show different visualisations of data and potential experiences.

MVVM, design time data, and Blendability

DesigntimedataprojectstructureWith 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.

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.
Designtimedata

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.

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.

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.

Xaml data for shopping cart

<local:ShoppingCartViewModel xmlns:local="clr-namespace:DesignDataSample;assembly=DesignDataSample">
    <local:ShoppingCartViewModel.ShoppingCart xmlns:local="clr-namespace:DesignDataSample;assembly=DesignDataSample">
        <local:ShoppingCart>
            <local:ShoppingCart.Items>
                <local:ShoppingCartItem ItemName="Book Name 1"
                                        ItemDescription="A very nice book!"
                                        ItemImage="MySampleDataImages/Tree.jpg" />
                <local:ShoppingCartItem ItemName="Book Name 2"
                                        ItemDescription="A very nice book!"
                                        ItemImage="MySampleDataImages/Tree.jpg" />
                <local:ShoppingCartItem ItemName="Book Name 3"
                                        ItemDescription="A very nice book!"
                                        ItemImage="MySampleDataImages/Tree.jpg" />
                <local:ShoppingCartItem ItemName="Book Name 4"
                                        ItemDescription="A very nice book!"
                                        ItemImage="MySampleDataImages/Tree.jpg" />
            </local:ShoppingCart.Items>
        </local:ShoppingCart>
    </local:ShoppingCartViewModel.ShoppingCart>
</local:ShoppingCartViewModel>

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.

Xaml Source code for the control

<UserControl
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             x:Class="DesignDataSample.ShoppingCartView"
             d:DataContext="{d:DesignData Source=ShoppingCartSampleData.xaml}"
             DataContext="{Binding Path=ShoppingCartViewModel, Source={StaticResource serviceLocator}}" 
             Height="347" 
             Width="494">

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.

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.

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.

Refactored mock service class with new virtual methods

    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));
            }
        }
    }

The new mock service class which is used specifically for working with Blend

namespace DesignDataSample.Mocks
{
    public class MockShoppingCartServiceDesignData : MockShoppingCartService
    {
        public override void RetrieveShoppingCart()
        {
            this.OnGetShoppingCartCompleted(null, MockShoppingCartData.CreateShoppingCartDesigntime());
        }
    }
}

How we can use ninject to inject the service we want to use, design time data, mock or real.

this.Bind<IShoppingCartService>().To<MockShoppingCartService>().OnlyIf(c => isBrowser);
this.Bind<IShoppingCartService>().To<MockShoppingCartServiceDesignData>().OnlyIf(c => isBlend);
this.Bind<IShoppingCartService>().To<ShoppingCartService>().OnlyIf(c => isBrowser);
this.Bind<ShoppingCartViewModel>().ToSelf();

Xaml code for how we leverage the data context and the new design time data context for providing contextual data.

<UserControl
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             x:Class="DesignDataSample.ShoppingCartView"
             d:DataContext="{Binding Path=ShoppingCartViewModel, Source={StaticResource serviceLocator}}"
             DataContext="{Binding Path=ShoppingCartViewModel, Source={StaticResource serviceLocator}}" Height="347" Width="494">
<!--d:DataContext="{d:DesignData Source=ShoppingCartSampleData.xaml}"-->
    <UserControl.Resources>
        <DataTemplate x:Key="ShoppingCartItemTemplate">
            <Grid Height="50">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="50" />
                    <ColumnDefinition Width="*" />
                </Grid.ColumnDefinitions>
                <Grid.RowDefinitions>
                    <RowDefinition Height="*" />
                    <RowDefinition Height="*" />
                </Grid.RowDefinitions>

                <Image Source="{Binding ItemImage}"
                       Grid.RowSpan="2" />
                <TextBlock Text="{Binding ItemName}"
                           Grid.Column="1"
                           Margin="4,0,0,0" />
                <TextBlock Text="{Binding ItemDescription}"
                           Grid.Column="1"
                           Grid.Row="1"
                           Margin="4,0,0,0" />
            </Grid>
        </DataTemplate>
    </UserControl.Resources>

    <Grid x:Name="LayoutRoot"
          Background="#FFB2B2B2">
        <Grid.ColumnDefinitions>
            <ColumnDefinition />
            <ColumnDefinition Width="129" />
            <ColumnDefinition Width="121" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition />
            <RowDefinition Height="50" />
        </Grid.RowDefinitions>
        <ListBox Margin="8,8,8,26"
                 Grid.ColumnSpan="3"
                 ItemsSource="{Binding Mode=OneWay, Path=ShoppingCart.Items}"
                 ItemTemplate="{StaticResource ShoppingCartItemTemplate}" />
        <TextBlock Grid.Row="1"
                   Text="Total Items:"
                   TextWrapping="Wrap"
                   Grid.Column="1" />
        <TextBlock Grid.Column="2"
                   Grid.Row="1"
                   Text="{Binding ShoppingCart.Items.Count}"
                   TextWrapping="Wrap" />
    </Grid>
</UserControl>

 

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.

You can download the source from my Skydrive.