Silverlight 4, MEF and MVVM: loading different “MEF Modules” in the same Container

Today I’ve finally found some time to make modifications in the “MEF MVVM” project on Codeplex in order to:

  • create a new module using WCF RIA Services and dynamically load this it inside the “MEF module container” described in the previous post;
  • use the INavigationContentLoader interface and MEF Metadata to share the same container for the various “MEF Modules”;
  • use the new Cosmopolitan theme available for Silverlight Navigation applications;
  • refactor the code of the ViewModel base class using the one available in the latest Prism drops;
  • refactor unit tests inserting an apposite Mock service.

The source code is available for download on Codeplex.

Happy Silverlighting!

Windows Phone 7 Multi-Touch Behavior videos #wp7dev

Some time ago I’ve started a Codeplex project dedicated to multi-touch, available on Codeplex at

The goal of this project is to provide an unified interface for Silverlight, WPF and Windows Phone 7 in order to provide multi-touch support using a visual approach via the concept of Behavior available in Expression Blend.

Recently I had the honor to welcome in the project a pillar of the Silverlight community, Laurent Bugnion, who is working on the Windows Phone 7 version of the Behavior:

Laurent has just published on his blog two awesome videos to get started with this new Behavior, and has created a specific section on his site to announce updates and publish content.

A special thanks to Pete Blois of the Expression Blend team for his help and contributions.

Stay tuned as we’ll be posting updates very soon 🙂

Happy Silverlighting!

Enabling Multi-touch gestures in WPF using Expression Blend 4 RC and the TranslateZoomRotate behavior

I’ve already blogged about adding multi-touch support to Silverlight applications using Blend behaviors (you can also read my italian language article).

This is a powerful and simple approach which is now available in WPF using Expression Blend 4 RC and the TranslateZoomRotateBehavior.

Let’s try to build a simple example:

1 – Open Expression Blend and create a new WPF project:

 2 – Drag a Rectangle in the MainWindows.xaml:

3 – Let’s add multi-touch gestures and inertia effects to the rectangle selecting the Assets->Behavior tab and dragging the TranslateZoomRotateBehavior inside the rectangle:

4 – Let’s examine the Properties:

It’s possible to set the supported gestures (All, None, TranslateX, TranslateY, Rotate, Scale), the constrainToParentBounds modality, the Minimum, Maximum Scale and the Rotational and Translate Friction associated to the inertia.

Let’s select the constrainToParentBounds check box and run the project using the Project->Run Project menu:

Cool, Multi-touch and inertia effects are now enabled for the rectangle without writing a line of code!

And this is the generated xaml:

	xmlns=" 2006/xaml/presentation"
	xmlns:x=" 2006/xaml"
	xmlns:i=" 2010/interactivity"
	xmlns:ei=" 2010/interactions"
	Width="640" Height="480">

	<Grid x:Name="LayoutRoot">
		<Rectangle Margin="149,106,133,191" Stroke="Black">
				<ei:TranslateZoomRotateBehavior ConstrainToParentBounds="True"/>
				<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
					<GradientStop Color="Black" Offset="0"/>
					<GradientStop Color="#FF8F98CA" Offset="1"/>

The source code of the project is available for download here.

Slides and Code from my Silverlight 4 – MEF webcast

Here you can find the sample code and slides (in italian) from my webcast around Silverlight 4 and MEF for the local XEdotNET user group.

The samples contain the following topics:

  • Simple composition using the CompositionInitializer;
  • Multiple Exports;
  • Metadata;
  • Custom Attributes;
  • Dynamic object creation with ExportFactory;
  • Simple MVVM example using MEF;
  • MEF, MVVM and PRISM EventAggregator;
  • Dynamic XAP loading using DeploymentCatalog;
  • MEF, MVVM and Blend Sample Data.

Hope this helps and Happy Silverlighting!

Microsoft Silverlight 4 Business Application Development: Beginners Guide

The new book “Microsoft Silverlight 4 Business Application Development: Beginners Guide” by Cameron Albert and Frank LaVigne is now available:

This is the overview taken from the publisher site:

  • An introduction to building enterprise-ready business applications with Silverlight quickly.
  • Get hold of the basic tools and skills needed to get started in Silverlight application development.
  • Integrate different media types, taking the RIA experience further with Silverlight, and much more!
  • Rapidly manage business focused controls, data, and business logic connectivity.
  • A suite of business applications will be built over the course of the book and all examples will be geared around real-world useful application developments, enabling .NET developers to focus on getting started in business application development using Silverlight.

I’ve just received my copy and I’m looking forward to read it in the next days!

Update: review on Amazon

I’ve just inserted a review on Amazon, you can read it here:

A different approach for learning Silverlight

The writing style is clear. The authors guide the reader in learning many topics about Silverlight by using practical examples, starting from the basics and arriving to Rich-Media, Deep Zoom, WCF RIA Services and an introduction to the Expression suite.
The included source code for the WCF RIA examples is not updated for the latest version of the framework, however it can be easily upgraded to work with Silverlight 4 RTW.
It’s not a complete reference to Silverlight 4 but it contains useful samples for real scenarios.”

Silverlight 4, MEF and MVVM: MEFModules, Dynamic XAP Loading and Navigation Applications

In the last example I’ve implemented a new “MEF Module” organized with a MVVM approach and using Prism Event Aggregator to exchange messages.

This new module could be used to partititon the application in several XAPs composed dynamically at run-time using MEF, the new DeploymentCatalog and the Navigation features available in Silverlight.

To start I’ve created a new “Silverlight Navigation Application” which produces a complete application with ready-to-use navigation and localization.

Then I’ve inserted a new “Silverlight User Control” inside the “Views” folder and named it “MEFModuleContainer“: this one is called by the navigation framework and is responsible to load dynamically the module using the MEF “DeploymentCatalog“.

This is the XAML of the container:

<StackPanel x:Name="ContentStackPanel">
    <TextBlock x:Name="HeaderText" Style="{StaticResource HeaderTextStyle}"
               Text="MEF Module container"/>
    <TextBlock x:Name="ContentText" Style="{StaticResource ContentTextStyle}"
               Text="MEF content"/>
    <ItemsControl x:Name="content"/>

Our “MEF Module” is hosted in a “ItemsControl” using the “Items” property:

public MEFModuleContainer()



public IDeploymentCatalogService CatalogService { get; set; }

[ImportMany(AllowRecomposition = true)]
public Lazy<UserControl>[] MEFModuleList { get; set; }

#region IPartImportsSatisfiedNotification Members

public void OnImportsSatisfied()


In order to use the DeploymentCatalog, it’s necessary to define an interface IDeploymentCatalogService (read this post by Glenn Block for more information about it):

public interface IDeploymentCatalogService
    void AddXap(string uri, Action<AsyncCompletedEventArgs> completedAction = null);
    void RemoveXap(string uri);

and implement it in the class “DeploymentCatalogService“:

public class DeploymentCatalogService : IDeploymentCatalogService
    private static AggregateCatalog _aggregateCatalog;

    Dictionary<string, DeploymentCatalog> _catalogs;

    public DeploymentCatalogService()
        _catalogs = new Dictionary<string, DeploymentCatalog>();

    public static void Initialize()
        _aggregateCatalog = new AggregateCatalog();
        _aggregateCatalog.Catalogs.Add(new DeploymentCatalog());

    public void AddXap(string uri, Action<AsyncCompletedEventArgs> completedAction = null )
        DeploymentCatalog catalog;
        if (!_catalogs.TryGetValue(uri, out catalog))
            catalog = new DeploymentCatalog(uri);
            if (completedAction != null)
                catalog.DownloadCompleted += (s, e) => completedAction(e);
                catalog.DownloadCompleted += catalog_DownloadCompleted;

            _catalogs[uri] = catalog;

    void catalog_DownloadCompleted(object sender, AsyncCompletedEventArgs e)
        if (e.Error != null)
            throw e.Error;

    public void RemoveXap(string uri)
        DeploymentCatalog catalog;
        if (_catalogs.TryGetValue(uri, out catalog))

The DeploymentCatalogService is initialized during the Application startup in this way:

private void Application_Startup(object sender, StartupEventArgs e)
    //Initialize the DeploymentCatalogService for MEF
    this.RootVisual = new MainPage();

When the user clicks on the Navigation bar, the container is loaded and filled with the content of the external XAP, all managed by MEF:

So we have a Navigation application which can dynamically load external “MEFModules” organized with a MVVM approach, contained in external XAPs and using an Event Aggregator to exchange messages, all managed by MEF.

This application can be easily extended inserting WCF RIA Services and/or Blend sample data for the design mode.

As usually the sample code is available for download here and will be soon available in the CodePlex project “MEF MVVM” –

Happy Silverlighting!

Experiments with Multi-touch: A Windows Phone Manipulation sample

I’ve just updated the project on CodePlex to Silverlight 4 RC and added a new sample of multi-touch using Windows Phone 7 manipulation capabilities starting from this how-to available in MSDN – “How to: Handle Manipulation Events” –

The modified sample uses an Image to illustrate the possibility to move and scale objects in the Windows Phone emulator using the “ManipulationDelta” event:

These are the steps to follow in order to enable Scale and Translation gestures in a Windows Phone application:

  • Just create a new “Windows Phone Application” from Visual Studio and then add an Image control in the MainPage.xaml using this code
<Canvas x:Name="ContentCanvas" Grid.Row="1">
    <Image Source="Images/Desert.jpg" Canvas.Left="99" Canvas.Top="100"
           x:Name="image1" Stretch="Fill" Width="300">
  • Then add an event handler for the “ManipulationDelta” event for applying a Scale and a Translate transform using the CompositeTransform available in Silverlight 4:
public MainPage()

    SupportedOrientations = SupportedPageOrientation.Portrait | SupportedPageOrientation.Landscape;

    ManipulationDelta += image1_ManipulationDelta;
    _compositeTransform=new CompositeTransform();
    image1.RenderTransform = _compositeTransform;

private CompositeTransform _compositeTransform;

void image1_ManipulationDelta(object sender, ManipulationDeltaEventArgs e)
    // Scale
    if (e.DeltaManipulation.Scale.X!=0)
       _compositeTransform.ScaleX *= e.DeltaManipulation.Scale.X;
    if (e.DeltaManipulation.Scale.Y!=0)
        _compositeTransform.ScaleY *= e.DeltaManipulation.Scale.Y;

    // Translation
    _compositeTransform.TranslateX += e.DeltaManipulation.Translation.X;
    _compositeTransform.TranslateY += e.DeltaManipulation.Translation.Y;

The source code is available for download from CodePlex:

Happy Silverlighting!

Multi-Touch enabling Silverlight Simon using Blend behaviors and the Surface sample for Silverlight

I have already blogged about using Blend behaviors to add Multi-Touch gestures and inertia effects to a generic Silverlight user control, so I wanted to use the same approach to add the same behaviors to the CodePlex project Simon.

I think that inserting multi-touch manipulation effects to a Silverlight application using Blend behaviors is an elegant way which makes the code very clear and readable.

To start you need to download the Multi-touch manipulation and inertia behavior (wow, more than 7000 downloads, great feedback! :)), which I already published on the Expression site.

This behavior is based on the code available in the Microsoft Surface Manipulations and Inertia Sample for Microsoft Silverlight, in my opinion the best example available for using multi-touch in Silverlight at this time.

The solution available contains a project named “MultiTouch.behaviors.Silverlight” which must be included in your application to enable the multi-touch functionalities.

To make the Silverlight/Blend Behavior work with Simon I’ve modified some code relative to the Zoom gesture in order to use a ScaleTransform (check out the source code on CodePlex:

To use the Behavior in XAML just add a reference to the “MultiTouch.Behaviors.Silverlight” project and use the following code:

<UserControl x:Class="SimonSilverlight.MainPage"
    xmlns:interactivity="clr-namespace:System.Windows.Interactivity; assembly=System.Windows.Interactivity"
    xmlns:multitouch="clr-namespace:MultiTouch.Behaviors.Silverlight; assembly=MultiTouch.Behaviors.Silverlight">
    <uc:Simon x:Name="Says">
            <multitouch:MultiTouchManipulationBehavior InertiaEnabled="True" TouchRotateEnabled="True"
                       TouchScaleEnabled="True" TouchTranslateEnabled="True"/>

Since we are using a Blend Behavior, we can also open the solution in Expression Blend, select the “MultiTouchManipulationBehavior” from the “Assets” section and drag it over the Simon control:

Happy Silverlighting!

Silverlight 4, MEF and MVVM: EventAggregator, ImportingConstructor and Unit Tests

I had recently the possibility to use MEF and Silverlight in a sample project together with Prism, this is for sure a great combination of frameworks for bulding applications using maintainable and extensible code. I don’t think that using MEF excludes the usage of Prism and vice versa,  the choice should be pondered and analyzed accordingly to the problem to solve.

Starting from the previous experiments, I decided to refactor and cleanup the MVVM approach in order to:

  • obtain simpler code;
  • inserting an EventAggregator managed by MEF to exchange messages;
  • maintaining the Visual Studio designer/Blend support;
  • trying a simple unit test using the framework available in the Silverlight Toolkit.
  1. Using the EventAggregator

The first step is inserting in the project the Prism EventAggregator downloading the “Microsoft.Practices.Composite.dll” and “Microsoft.Practices.Composite.Presentation.dll” libraries from the Prism site on Codeplex.

It’s now possible to make available in the application an instance of it using this syntax:

public class EventAggregatorProvider
   public IEventAggregator eventAggregator { get { return new EventAggregator(); } }

In this way we are able to import it in the ViewModel class using an [ImportingConstructor] attribute:

public MainPageViewModel(IEventAggregator eventAggregator, IDataItemsService dataItemsService)
   _eventAggregator = eventAggregator;
   _dataItemsService = dataItemsService;

When an [ImportingConstructor] is found, MEF looks for an [Export] for each parameter available in the constructor, in this case we must have exported an “IEventAggregator” and an “IDataItemsService”.

We are now able to access the instance of the EventAggregator and Publish/Subscribe to events using a syntax like:

//Call the Service

//Subscribe to the "DataItemsReceivedEvent"

_eventAggregator. GetEvent(). Subscribe(
    dataItemsReceived =>
        this.dataItems = dataItemsReceived;

In this case we are receiving the result of the async calls via the EventAggregator and a DataItemsReceivedEvent:

public class DataItemsReceivedEvent : CompositePresentationEvent {  }

DataItemsService code publishing the Event:

//Initialize the collection
DataItemWcfService.DataItemServiceClient svc = new DataItemWcfService.DataItemServiceClient();
svc.GetDataItemsCompleted += (s1, e1) =>
    if (e1.Result != null)
        var dataItems = new DataItems();
        e1.Result.ToList().ForEach(d =>
            dataItems.Add(new DataItem() { Description = d.Description });

        //Publish the DataItems
        _eventAggregator. GetEvent(). Publish(dataItems);

        isLoading = false;
isLoading = true;

2. Maintaining the Visual Studio designer/Blend support

In the previous experiments I enabled design-time data by inserting a new ViewModel class which can create some confusion, so I decided to skip this step and using a unique ViewModel following this approach:

  • the ViewModel parameterless constuctor contains the initialization for data to be used during design time and tests;
  • the other constructor marked with the MEF [ImportingConstructor] attribute enables initialization of services and event aggregator.
public MainPageViewModel(IEventAggregator eventAggregator, IDataItemsService dataItemsService)
    _eventAggregator = eventAggregator;
    _dataItemsService = dataItemsService;

3 – Unit Test

To verify the approach described, I’ve inserted a new “Silverlight Unit Test project” to the solution (note that the “Silverlight Toolkit” must be installed to use this feature) and then a simple Test method containing the following code:

public class Tests
    [Description("Test the creation of a ViewModel and the initialization of Design/Test Data")]
    public void TestViewModelCreation()
        var vm = new MainPageViewModel();
        Assert.AreEqual(vm.dataItems.Count, 2);

Since MEF is only used to compose run-time Parts, I’m not using it in the Unit Tests.

So we have now a new piece of code, which I’ve called a “MEFModule” organized with a MVVM approach and ready for design-time support, unit tests and extensibility: ready to be inserted in a Navigation applicationdynamically loaded and enabled for design time using Blend Sample Data, stay tuned.

The source code is available for download here.

Happy Silverlighting!

A Silverlight / Expression Blend behavior to add Multi-Touch Manipulation and Inertia

I’ve updated the behavior available in the Expression Community gallery adding Multi-Touch manipulation (translation, rotation and zoom) and inertia effects using code from the Surface Manipulations and Inertia Sample for Microsoft Silverlight.

To enable Multi-Touch in your code simply download the behavior from here, add the project “MultiTouch.Behaviors.Silverlight” to a Visual Studio solution and then enable the gestures in XAML:

<UserControl x:Class="SilverlightMultiTouch.MainPage"
xmlns:interactivity="clr-namespace:System.Windows.Interactivity; assembly=System.Windows.Interactivity"
xmlns:behaviors="clr-namespace:MultiTouch.Behaviors.Silverlight; assembly=MultiTouch.Behaviors.Silverlight"

  <Image Source="Images/Desert.jpg">
         <behaviors:MultiTouchManipulationBehavior InertiaEnabled="True" TouchRotateEnabled="True" TouchTranslateEnabled="True" TouchScaleEnabled="True"/>

  <Image Source="Images/Jellyfish.jpg">
         <behaviors:MultiTouchManipulationBehavior InertiaEnabled="True" TouchRotateEnabled="True" TouchTranslateEnabled="True" TouchScaleEnabled="True"/>

The MultiTouchManipulationBehavior also contains some dependency properties (TouchRotateEnabled, TouchTranslateEnabled, TouchScaleEnabled and InertiaEnabled) to enable the corresponding gestures.

The example contains Multi-Touch manipulations applied to some Image controls and a Smooth streaming player of the Silverlight Media Framework.

I’ve also posted to CodePlex a sample using WPF 4 based on the article “Introduction to WPF 4 Multitouch” by Jaime Rodriguez.

Hope this helps and Happy Silverlighting!