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 http://multitouch.codeplex.com.

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 http://www.galasoft.ch/touch 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:

<Window
	xmlns="http://schemas.microsoft.com/winfx/ 2006/xaml/presentation"
	xmlns:x="http://schemas.microsoft.com/winfx/ 2006/xaml"
	xmlns:i="http://schemas.microsoft.com/expression/ 2010/interactivity"
	xmlns:ei="http://schemas.microsoft.com/expression/ 2010/interactions"
	x:Class="WpfApplication1.MainWindow"
	x:Name="Window"
	Title="MainWindow"
	UseLayoutRounding="True"
	Width="640" Height="480">

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

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!

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: http://simon.codeplex.com).

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">
....
<Canvas>
    <uc:Simon x:Name="Says">
        <interactivity:Interaction.Behaviors>
            <multitouch:MultiTouchManipulationBehavior InertiaEnabled="True" TouchRotateEnabled="True"
                       TouchScaleEnabled="True" TouchTranslateEnabled="True"/>
        </interactivity:Interaction.Behaviors>
    </uc:Simon>
</Canvas>

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
{
   [Export(typeof(IEventAggregator))]
   public IEventAggregator eventAggregator { get { return new EventAggregator(); } }
}

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

[ImportingConstructor]
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
_dataItemsService.GetDataItems();

//Subscribe to the "DataItemsReceivedEvent"

_eventAggregator. GetEvent(). Subscribe(
    dataItemsReceived =>
    {
        this.dataItems = dataItemsReceived;
    },
    true
);

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;
    }
};
svc.GetDataItemsAsync();
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.
[ImportingConstructor]
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:

[TestClass]
public class Tests
{
    [TestMethod]
    [Description("Test the creation of a ViewModel and the initialization of Design/Test Data")]
    public void TestViewModelCreation()
    {
        var vm = new MainPageViewModel();
        Assert.IsNotNull(vm);
        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 application, dynamically 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"
...
>

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

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

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!

Experiments using MEF, MVVM and Silverlight 4 Beta – Part 6: Design-mode ViewModel and calling a WCF Service

Note – this is a multi part post:

Today I had the opportunity to take a look at the code written in the previous posts and insert some new stuff in order to modify the project and make new experiments about:

  1. using a different ViewModel class for the design-time and run-time;
  2. using MEF combined with the new implicit styles feature available in Silverlight 4 Beta to initialize the DataContext of the View at run-time;
  3. retrieve the data using an async call to a WCF service and passing back the results to the VM via MEF.

1 – Using different VM classes

To accomplish this task I’ve defined a new interface named IMainPageViewModel defining these members:

/// MainPage ViewModel interface
public interface IMainPageViewModel : IViewModelBase
{
    string aViewModelProperty { get; set; }
    DataItems dataItems { get; set; }
    ICommand addDataItemCommand { get; }
}

This new interface is then implemented by two classes named ViewModels.DesignMode.MainPageViewModel and ViewModels.MainPageViewModel:

/// ViewModel for the "MainPageView" used in design-mode
public class MainPageViewModel : ViewModelBase, IMainPageViewModel
{
    public MainPageViewModel()
    {
        //Initialize the properties with test data if design mode
        aViewModelProperty = "Value - Design Mode";

        //Initialize the "dataItems" property
        dataItems = new DataItems();
        dataItems.Add(new DataItem() { Description = "Sample Data Item 1 - Design Mode" });
        dataItems.Add(new DataItem() { Description = "Sample Data Item 2 - Design Mode" });
    }

    public string aViewModelProperty { get; set; }

    public DataItems dataItems { get; set; }

    public ICommand addDataItemCommand { get; set; }
}
/// ViewModel class for the "MainPageView" using MEF
[PartCreationPolicy(CreationPolicy.NonShared)]
[Export(typeof(MainPageViewModel))]
public class MainPageViewModel : ViewModelBase, IMainPageViewModel
{
    public MainPageViewModel() {  }

    [Import("aViewModelPropertyTextProvider")]
    public string aViewModelProperty { get; set; }

    [Import(typeof(WcfDataItems))]
    public DataItems dataItems { get; set; }

    [Import(typeof(ICommand))]
    public PartCreator addDataItemCommandCreator { get; set; }

    private ICommand _addDataItemCommand;
    public ICommand addDataItemCommand
    {
        get {
            if (_addDataItemCommand==null)
                _addDataItemCommand = addDataItemCommandCreator.CreatePart().ExportedValue;
            return _addDataItemCommand;
        }
    }
}

The first one is associated with the View at design-time using an attached property which permits to bind an instance only at design time using this xaml (usually you should use <d:DesignProperties.DataContext>, here we are experimenting, of course):



    <!-- Design time DataContext -->
    
        
    

    ........

DesignTimeDataContext attached dependency property:

/// DesignDataContext Attached Dependency Property
public static readonly DependencyProperty DesignDataContextProperty =
    DependencyProperty.RegisterAttached("DesignDataContext", typeof(object), typeof(Page),
        new PropertyMetadata((object)null,
            new PropertyChangedCallback(OnDesignDataContextChanged)));

/// Gets the DesignDataContext property.
public static object GetDesignDataContext(DependencyObject d)
{
    return (object)d.GetValue(DesignDataContextProperty);
}

/// Sets the DesignDataContext property.
public static void SetDesignDataContext(DependencyObject d, object value)
{
    d.SetValue(DesignDataContextProperty, value);
}

/// Handles the DesignDataContext property changes
private static void OnDesignDataContextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    FrameworkElement element = (FrameworkElement)d;

    //Get the ViewModel instance only in design mode
    if ((Application.Current == null) || (Application.Current.GetType() == typeof(Application)))
       element.DataContext = e.NewValue;
}

And this is the design-time mode in Blend using the new attached property:

MEFMVVM Blend

2 – MEF and implicit styles

The new implict styles feature available in Silverlight 4 beta is used to initialize the DataContext of the MainPageView type in a declarative way in App.xaml:




    <!-- Run-time DataContext composed using MEF -->

In this case I’ve modified the MainPageViewModelMEFProvider class and inserted a new IViewModelProvider interface in order to obtain the instance of the ViewModel initialized by MEF:

/// Interface for the ViewModelProvider
public interface IViewModelProvider
{
    object GetViewModel { get; }
}
/// Get the ViewModel instance using MEF
public class MainPageViewModelMEFProvider : IViewModelProvider
{
    public MainPageViewModelMEFProvider() { }

    [Import(typeof(MainPageViewModel))]
    public IViewModelBase ViewModel { get; set; }

    /// Get the Instance of the ViewModel using MEF
    public object GetViewModel
    {
        get
        {
           PartInitializer.SatisfyImports(this);
           return ViewModel;
        }
    }
}

3 – retrieve the data using an async call to a WCF service

I’ve added to the solution a simple WCF service which returns a collection of DataItems:

[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class DataItemService : IDataItemService
{
    [OperationContract]
    public List GetDataItems()
    {
        // Add your operation implementation here
        return new List()
        {
            new DataItemFromService() {Description="DataItem from service 1"},
            new DataItemFromService() {Description="DataItem from service 2"},
            new DataItemFromService() {Description="DataItem from service 3"}
        };
    }
}

interface IDataItemService
{
    List GetDataItems();
}

public class DataItemFromService
{
    public string Description { get; set; }
}

Since the project uses MEF composition and [Import] /[Export] attributes to initialize all the members of the VM class, I’ve used the same approach for the dataItems collection, retrieving data from an async call to the WCF service using a WcfDataItems class:

/// A sample collection of DataItems from WCF
[Export(typeof(WcfDataItems))]
public class WcfDataItems : DataItems
{
    public WcfDataItems()
    {
        //Initialize the collection
        DataItemWcfService.DataItemServiceClient svc = new DataItemWcfService.DataItemServiceClient();
        svc.GetDataItemsCompleted += (s1, e1) =>
        {
            if (e1.Result != null)
                e1.Result.ToList().ForEach(d =>
                    {
                        //Retrieve a new DataItem
                        DataItem di = DataItemCreator.CreatePart().ExportedValue;
                        di.Description = d.Description;
                        this.Add(di);
                    });
            isLoading = false;
        };
        svc.GetDataItemsAsync();
        isLoading = true;
    }

    [Import(typeof(DataItem))]
    public PartCreator DataItemCreator { get; set; }
}

The code is available for download here.

Happy Silverlighting!

Experiments using MEF, MVVM and Silverlight 4 Beta – Part 5: Enabling Blend and the Visual Studio designer

Note – this is a multi part post:

In the last post I’ve updated the sample project introducing PartCreator<T>, in this one I will illustrate a method to make available sample data during the editing of the solution in Blend or in the Visual Studio designer, in order to obtain a result like this (a similar approach is used in the awesome MVVM light toolkit by Laurent Bugnion):

MEFMVVM Blend

First of all, I’ve created a class ViewModelProvider to obtain dinamically an instance of the ViewModel and directly used in xaml to create the VM instance, in this way it’s possibile to see sample data during the design phase:

public class ViewModelProvider : IViewModelProvider
{
    public ViewModelProvider() { }

    [Import(typeof(MainPageViewModel))]
    public IViewModelBase mainPageViewModelProvider { get; set; }

    ///

    /// Get the Instance of the ViewModel
    /// 

    public IViewModelBase GetVMInstance
    {
        get
        {
            //Verify if Design Mode
            if ((Application.Current == null) || (Application.Current.GetType() == typeof(Application)))
            {
                return new MainPageViewModel();
            }
            else
            {
                //If not in Design Mode uses MEF to compose the objects
                PartInitializer.SatisfyImports(this);
                return mainPageViewModelProvider;
            }
        }
    }
}

I’ve not already found a method to activate MEF compositions during design time, so an instance of the ViewModel class is explicitely created in code if we are in the tool designers, otherwise SatisfyImports() executes the MEF magic as usually.

It’s now necessary to initialize the properties values in order to display sample data at design time, this step can be done in the constructor of the MainPageViewModel:

[PartCreationPolicy(CreationPolicy.NonShared)]
[Export(typeof(MainPageViewModel))]
public class MainPageViewModel : ViewModelBase, IMainPageViewModel
{
    ///
    /// Default constructor
    ///
    public MainPageViewModel()
    {
        if ((Application.Current == null) || (Application.Current.GetType()==typeof(Application)))
        {
            //Initialize the properties with test data if design mode
            aViewModelProperty = "Value - Design Mode";
            dataItems = new SampleDataItems(); dataItems.ToList().ForEach(d=>d.Description+=" - Design Mode");
        }
    }

    ///
    /// A sample property
    ///
    [Import("aViewModelPropertyTextProvider")]
    public string aViewModelProperty { get; set; }

    ///
    /// A sample collection
    ///
    [Import(typeof(DataItems))]
    public DataItems dataItems { get; set; }

    ///
    /// A Part creator for the addDataItemCommandCreator
    ///
    [Import(typeof(ICommand))]
    public PartCreator addDataItemCommandCreator { get; set; }

    private ICommand _addDataItemCommand;
    public ICommand addDataItemCommand
    {
        get {
            if (_addDataItemCommand==null)
                _addDataItemCommand = addDataItemCommandCreator.CreatePart().ExportedValue;
            return _addDataItemCommand;
        }
    }
}

Inside Visual Studio, it’s now possibile to edit the User Interface and visualize the sample data defined in the constructor:

VisualStudio2010

The source code is available for download here.

Hope this helps!

Experiments using MEF, MVVM and Silverlight 4 Beta – Part 4: Part Creator

Note – this is a multi part post:

In the last post I’ve updated the MEF MVVM example inserting some PartCreator<T> experiments and I’ve received some feedback about its usage in the ViewModel instance initialization, so I decided to build a new sample in which PartCreator<T> is used to dynamically create objects to be inserted in a collection available in the ViewModel.

The VM instance is now initialized using an import attribute:

/// <summary>
/// Get the ViewModel instance
/// </summary>
public class ViewModelProvider
{
    public ViewModelProvider() { }

    [ImportMainPageVMAttribute]
    public object mainPageViewModelProvider { get; set; }

    /// <summary>
    /// Get the imported Instance of the ViewModel
    /// </summary>
    public object GetVMInstance
    {
        get
        {
            PartInitializer.SatisfyImports(this);
            return mainPageViewModelProvider;
        }
    }
}

PartCreator<T> is now used in a new AddDataItemCommand which updates dynamically a collection available in the ViewModel class:

/// <summary>
/// A simple Command to add a new DataItem in the ViewModel collection
/// </summary>
[PartCreationPolicy(CreationPolicy.NonShared)]
[Export(typeof(ICommand))]
public class AddDataItemCommand : ICommand
{
    public bool CanExecute(object parameter)
    {
        return true;
    }

    public event EventHandler CanExecuteChanged;

    public void Execute(object parameter)
    {
        if (parameter != null)
            if (parameter is string)
            {
                var dataItem = DataItemCreator.CreatePart().ExportedValue;
                dataItem.Description = (string)parameter;
                viewModel.dataItems.Add(dataItem);
            }
    }

    [ImportMainPageVMAttribute]
    public MainPageViewModel viewModel { get; set; }

    [Import(typeof(DataItem))]
    public PartCreator<DataItem> DataItemCreator { get; set; }
}

MEF

The source code is available for download here.

Happy Silverlighting!

Experiments using MEF, MVVM and Silverlight 4 Beta – Part 3: Part Creator and Creation Policy

Note – this is a multi part post:

In the last post I’ve inserted custom attributes in my MVVM implementation using MEF, in the meantime some awesome discussions and inputs on Twitter by Glenn Block have highlighted new interesting scenarios.

First of all, object instances are shared by default in MEF, however you can change this behaviour using a dedicated attribute named PartCreationPolicy during the export phase:

[PartCreationPolicy(CreationPolicy.NonShared)]
[ExportMainPageVMAttribute]
public class MainPageViewModel : ViewModelBase
{ .... class definition here .... }

In this way, all the ViewModel instances exported by MEF will be not shared and different views shall use different VM objects without any side-effect.

Another rule of thumb is avoiding calling the container directly in order to simplify architecture, as stated in this great article by Nicholas Blumhardt. This step requires the introduction of a new actor available in MEF: the declarative context adapter PartCreator<T>.

The first place in which I’ve used PartCreator<T> is in the code for the composition phase:

public MainPageView()
{
   InitializeComponent();

   PartInitializer.SatisfyImports(this);
   this.DataContext = mainPageViewModelCreator.CreatePart().ExportedValue;
}

[ImportMainPageVMAttribute]
public PartCreator<object> mainPageViewModelCreator { get; set; }

The VM instance is now retrieved calling the CreatePart() method of the PartCreator, instead of calling directly the container.

The same approach is now used to retrieve the instances relative to the aViewModelProperty and aSampleCommand:

[PartCreationPolicy(CreationPolicy.NonShared)]
[ExportMainPageVMAttribute]
public class MainPageViewModel : ViewModelBase
{
    /// <summary>
    /// Default constructor
    /// </summary>
    public MainPageViewModel() { }

    /// <summary>
    /// A Part Creator for the aViewModelProperty
    /// </summary>
    [Import("aViewModelPropertyTextProvider")]
    public PartCreator<string> aViewModelPropertyCreator { get; set; }

    /// <summary>
    /// A sample property
    /// </summary>
    private string _aViewModelProperty;
    public string aViewModelProperty
    {
        get
        {
            if (_aViewModelProperty == null)
            {
                _aViewModelProperty = aViewModelPropertyCreator.CreatePart().ExportedValue;
            }
            return _aViewModelProperty;
        }
        set { _aViewModelProperty = value; NotifyPropertyChanged("aViewModelProperty"); }
    }

    /// <summary>
    /// A Part creator for the sample command
    /// </summary>
    [Import(typeof(ICommand))]
    public PartCreator<ICommand> aSampleCommandCreator { get; set; }

    /// <summary>
    /// A sample command
    /// </summary>
    public ICommand aSampleCommand
    {
        get
        {
            return aSampleCommandCreator.CreatePart().ExportedValue;
        }
    }

    /// <summary>
    /// A simple property
    /// </summary>
    private string _aSimpleProperty = "A simple property sample";
    public string aSimpleProperty {
        get { return _aSimpleProperty; }
        set { _aSimpleProperty = value; NotifyPropertyChanged("aSimpleProperty"); }
    }
}

The VM instance is then created in xaml using a ViewModelPartCreator class:

/// <summary>
/// Get the ViewModel instance via the PartCreator<T>
/// </summary>
public class ViewModelPartCreator
{
    public ViewModelPartCreator() { }

    [ImportMainPageVMAttribute]
    public PartCreator<object> mainPageViewModelPartCreator { get; set; }

    /// <summary>
    /// Get the imported Instance of the ViewModel
    /// </summary>
    public object GetVMInstance
    {
        get
        {
            PartInitializer.SatisfyImports(this);
            return mainPageViewModelPartCreator.CreatePart().ExportedValue;
        }
    }
}

MainPageView.xaml:

<UserControl x:Class="SL4_MVVM_MEF.Views.MainPageView"
    .......
    xmlns:partCreators="clr-namespace:SL4_MVVM_MEF.PartCreators"
    >

    <UserControl.DataContext>
        <partCreators:ViewModelPartCreator/>
    </UserControl.DataContext>

    <StackPanel>
        <StackPanel Orientation="Horizontal">
            <TextBox Text="A ViewModel property MEF imported:" FontWeight="Bold"/>
            <TextBox Text="{Binding GetVMInstance.aViewModelProperty}" Margin="10,0,0,0"/>
        </StackPanel>
        <StackPanel Orientation="Horizontal">
            <TextBox Text="A ViewModel simple property:" FontWeight="Bold"/>
            <TextBox Text="{Binding GetVMInstance.aSimpleProperty}" Margin="10,0,0,0"/>
        </StackPanel>
        <Button x:Name="CommandButton" Command="{Binding GetVMInstance.aSampleCommand}" CommandParameter="This is a Command parameter"
                Content="Click me!" Margin="0,10" Width="200"/>
    </StackPanel>
</UserControl>

As usually the source code is available for download here.

A special thanks to Glenn Block for the awesome suggestions on Twitter 🙂

Happy Silverlighting!