Tag Archives: View

Combining Silverlight Navigation Framework and Prism to create MVVM Applications – Introduction

This is introductory post for a series of posts where i will try to tackle the holy grail of MVVM applications – Navigation.

To do this I will be using Prism from Microsoft’s Patterns and Practices team (Silverlight version – latest drop) combined with Silverlight Navigation Framework and i will build small navigation framework on top of that.

If you are too busy to read this post and just want to see the result take a look at the current state of the sample Silverlight Prism Navigation application where you can see most of the important features of this small navigation framework (PrismExtensions.dll that contains all the framework code is 35.5 KB in size).

And for those of you with stronger nerves here is the real story:

Lately i have been playing with my old friend Prism and re-discovering how good it is for building MVVM Silverlight and WPF applications.

Out of the box you get a lot of things (and only few months ago i was trying to build all of this from scratch – you can see that from my earlier MVVM blog posts).

One of the things i like the most in Prism is the modularity concept and support for loading application modules dynamically from local/remote servers – on users/application request.

This allows developers to cut the application in modules with isolated functionality and on start load only mandatory parts and then load other modules only if users really needs/request them.

What really surprised me is that nobody has so far managed to combine Prism with Silverlight’s excellent Navigation Framework in a successful way so that is usable for real-life MVVM applications (at least i could not find any good examples on the web).

Prism has a concept of Regions and allows easy loading of Views into them but this is where it ends – there are no higher level concepts of navigation – this is why i decided to build some kind of Navigation framework on top of Prism – to fill that gap.

This is where the very important concept of Deep Linking comes into the story. I cannot imagine any serious Silverlight application without allowing users to bookmark pages in the browser, and to use the Back and Forward browser button to navigate though the UI, to manually ‘hack’ the URLs to load different data etc…

So this is something where Silverlight Navigation Framework can help us. It has built in support for all major browsers for browser history, it notifies the application about the browser URL change, there is HyperlinkButton control that has NavigateUri property where you can specify the application URL that will be loaded when user clicks on it (without full page reload off course – because only the fragment of the URL after # sign is changed) etc.

The only problem is that there is no easy way to combine Prism and Silverlight Navigation Framework.

Yes we can implement INavigationContentLoader and plug it into the Frame control but still we don’t have full control over the page/view loading process, we need additional Frame for each Region where we want to show Views etc.

So i decided to do a little research on how to simplify things and to create a small framework for Prism that will use Silverlight Navigation Framework to load Views into Prism Regions and enable Deep Linking, passing parameters to views, to allow integration with Prism modularity and allow deferred module loading etc – in other words all the features that one would expect to have in modern RIA Silverlight application.

Here are some features that i already support or will in near future:

  • it must be a simple (for the end user-developer) but full blown Navigation Framework for Prism Silverlight MVVM applications
  • it will support this main MVVM scenario: application will have one Main View (so called ‘Shell’) that will be loaded on start of the application and this will be the main ‘screen’ of the application that will have multiple regions where we can load Views. Only one region will be considered as Main Region and it will be ‘tied’ to the URL typed in the browser. Other regions will not update browsers URL or be affected by changes in the URL but application will be able to load Views into other regions – for example Widgets etc (i decided not to support Regions inside Views loaded into Regions on Main Region as this greatly simplifies the implementation and i don’t see a real usage scenario anyway –  instead of using Sub-Regions you can always use child Views inside of your View for that).
  • support for passing the parameters to the Views via browsers URL – every update in the URL of the browser will load appropriate view in Main Region (and pass parameters from URL to the Views ViewModel) and on the other hand, if some View is loaded to Main Region from code, this will reflect on the browser URL (including the parameters passed to View).
  • when View is loaded into region it will be connected to its ViewModel (set as its DataContext) – this is done automagically by the framework, user just needs to define the mapping between Views and View Models in the Module initialization – more details on that in later posts.
  • support for manually loading Views from ViewModels via code (not only via URLs) using the same framework – via some service like IPrismViewLoadingService
  • framework should include support for Prism deferred loading of application Modules – there should be easy way to load Prism Modules that are marked as OnDemand and they should be loaded either manually – from code or automagically – when user navigates to URL that should show View that is in module marked as ‘OnDemand’
  • there should be a way to define User Friendly URL’s – aliases for specific Views and Modules but some smart defaults should work out of the box by default like: “/Products/Detail/1234″  or “/ProductsModule/Details/1234″ etc – user should just type the URL in browser and Framework must load the Module if needed and then show the View (bound to its initialized ViewModel)
  • full support for navigation between Views using HyperlinkButton controls – for loading Views to Main Region and to other Regions
  • framework should be ‘opinionated’ regarding the way how it initializes and binds Views and their ViewModels – in our case it will be View-ViewModel-Marriage approach: there is separate service that initializes ViewModel and set it as DataContext of the View.
  • it should be simple to use for the end user-developer – smart defaults should work without any user configuration yet customization should be possible for advanced scenarios
  • whole solution should be based on services that implement defined interfaces – so that they can be easily changed with different implementations that user could plug via IOC – for example to easily change the parameters format from ‘parameterA/value1/parameterB/value2′ into ‘?parameterA=value1&parameterB/value2′ etc.

So this features should be enough to get us started but we can change this along the way if we see that its appropriate – if you have some suggestions – do let me know!

As you can see from the Sample Application I already have implemented most of these features and I will be finishing along the way as i write more posts in the future – what you can see in the demo right now is: Browser URL history integration (Deep Linking and Back/Forward buttons support), Loading Views with their corresponding ViewModels to Main Region and to secondary Regions, passing parameters to Views, asynchronous deferred loading of Modules/Views etc.

If some you know of some other Prism Navigation Framework that already has most of these features please let me know so i can stop doing this and enjoy real life :)

Otherwise see ya soon in the next part of this article series where i will explain all about this framework and share some code with usage scenarios.

Binding UI Events from View to commands in ViewModel in Silverlight 4

In previous two posts we covered wiring up the Views and ViewModels and Blendability and showing ModalDialogs in MVVM way.

Today we will touch another problem that people starting with MVVM very often fail to address properly:

Handling the UI Events of the View in the ViewModel while avoiding placing any logic in code behind of the View.

So our design goals for this post are:

  • We want to be able to wire-up UI Events to the commands in ViewModel via DataBinding in Xaml without any code behind in the View
  • View should not be aware of the ViewModel’s type or any other details of its existence – View should just use Silverlight’s DataBinding to access its ViewModel public properties (its DataContext) regardless of what is actually set to be there
  • We want to be able to handle any event that occurs in View (that includes not only Button clicks but also Mouse events,  Drag and Drop events, Loaded events etc).

When i was trying to solve this problem, i made a mistake.

I coupled the View with ViewModel,  made the View aware of the ViewModel via interface of the ViewModel.

View held the instance of ViewModel in its DataContext.

And then when some event fires in the View i would call a ViewModel method in code behind of the View (accessing it via local variable holding the ViewModel instance casted to interface that ViewModel is implementing).

While this approach works for all events in the View because you can create event handler for any View event, it has many drawbacks.

Main problems are:

  • View has to know about the ViewModel and it has to have a instance of the ViewModel injected somehow
  • we have to create event handlers in the View code behind .cs file for each event (this can be really boring, and im lazy to do repetitive code so that was really hard for me).

I didn’t like this solution at all and I immediately abandoned it.

Then i tried searching for possible solutions on the web and found the magical Expression Blend Samples.

Microsoft introduced Behaviors in Silverlight 3 with Blend 3 to help UI designers to have a flexible new way to add interactivity to applications.

Behaviors allow interactivity to be added to elements directly on the design surface in XAML without having to write additional code.

I will not go into details on Behaviors since there are tons of resources on the web on the subject,  you can read the original Blend 3 Behaviors announcement to get more info.

The great thing about Behaviors is that they introduced Triggers and very handy  EventTrigger and TriggerAction classes that are perfect match for our MVVM events scenario.

As you can read on the MSDN link EventTrigger  ‘Represents a trigger that applies a set of actions … in response to an event’.

So we can create a EventTrigger for some UI event in our View that will fire a custom TriggerAction that will call a method on our ViewModel with some parameters.

On the mentioned Expression Blend Samples page there is already implemented basic class for this – its called InvokeDataCommand and we will just customize it and extend (generalize it) so it serves our needs.

In the end we want to accomplish something like this in our View’s Xaml:

    <Interactivity:Interaction.Triggers>
        <Interactivity:EventTrigger EventName="MouseMove">
            <TriggerActions:MapMouseEventToCommand Command="{Binding Path=ShowMousePositionCommand}" />
        </Interactivity:EventTrigger>
    </Interactivity:Interaction.Triggers>

So this is instructing our View to call the command called ShowMousePositionCommand on its ViewModel when mouse pointer is moved over some control.

So lets get started!

First we need to create a command class that we will be able to call from our Events.

Silverlight has only partial support for commanding.

Until Silverlight 4 ICommand interface was available – but without any real support or use.
In Silverlight 4 this interface is supported by Button type controls in again partial way:  in ButtonBase class from which all button-like controls inherit, there are two properties: Command and CommandParameter that you can point to a command that implements ICommand interface and pass it some parameter.

This can be done via DataBinding and when you click the button this command will be executed with the specified parameter. No code solution, pure XAML!
The problem is that Silverlight 4 Beta does not offer any implementation of the ICommand interface so we have to do this by ourselves.

Here is the ICommand interface:

namespace System.Windows.Input
{
    public interface ICommand
    {
        bool CanExecute(object parameter);
        void Execute(object parameter);
        abstract event EventHandler CanExecuteChanged;
    }
}

So it basically defines a contract: Any command that will implement this interface we we will be able to query it if we can ececute it (CanExecute) and execute it with parameter via its Execute method,  also there is an event CanExecuteChanged so that anyone can subscribe to it in order to be notified if CanExecute status of command has changed (this is used by UI controls so that buttons become disabled if command is disabled etc).

But before we implement this lets make a slight modification and create another interface IDelegateCommand that will implement ICommand interface and just add one method RaiseCanExecuteChanged();

This new method is there so that we can invoke it from code if we know that status of our command has changed – so by invoking it we can notify the UI of this change.

So here is the new IDelegateCommand interface:

    public interface IDelegateCommand : ICommand
    {
        void RaiseCanExecuteChanged();
    }

And here is our generic version of DelegateCommand class that implements IDelegateCommand and ICommand:

  public class DelegateCommand<T> : IDelegateCommand
  {
    private readonly Action<T> executeAction;
    private readonly Func<T, bool> canExecuteAction;

    public DelegateCommand(Action<T> executeAction, Func<T, bool> canExecuteAction)
    {
      this.executeAction = executeAction;
      this.canExecuteAction = canExecuteAction;
    }

    public DelegateCommand(Action<T> executeAction) : this(executeAction, null)
    {
    }

    /// <summary>
    /// Defines the method that determines whether the command can execute in its current state.
    /// </summary>
    /// <returns>
    /// true if this command can be executed; otherwise, false.
    /// </returns>
    /// <param name="parameter">Data used by the command. If the command does not require data to be passed, this object can be set to null. </param>
    public bool CanExecute(object parameter)
    {
      if (canExecuteAction != null)
      {
        return canExecuteAction((T) parameter);
      }
      return true;
    }

    /// <summary>
    /// Defines the method to be called when the command is invoked.
    /// </summary>
    /// <param name="parameter">Data used by the command. If the command does not require data to be passed, this object can be set to null. </param>
    public void Execute(object parameter)
    {
      if (CanExecute(parameter))
      {
        executeAction((T) parameter);
      }
    }

    protected void OnCanExecuteChanged(object sender, EventArgs args)
    {
        var handler = this.CanExecuteChanged;
        if (handler != null)
        {
            handler(sender, args);
        }
    }

    public void RaiseCanExecuteChanged()
    {
        this.OnCanExecuteChanged(this, EventArgs.Empty);
    }

    public event EventHandler CanExecuteChanged;
  }

Its simple generic class that allows us to create commands on our ViewModels that will be triggered when needed.

I wont go into much details of this class since there are a lot of posts on this on the web. Be sure to check out Prism DelegateCommand version since my implementation is mostly based on their code.

Now that we have a way of specifying the commands that we will trigger let’s see how we will trigger them.

Back to our Behaviors:  We will create base generic class that will inherit from TriggerAction<FrameworkElement> and we will use this class to build specific TriggerActions for different UI events:

    public abstract class MapEventToCommandBase<TEventArgsType> : TriggerAction<FrameworkElement>
        where TEventArgsType : EventArgs
    {
        public static readonly DependencyProperty CommandProperty = DependencyProperty.Register("Command", typeof(IDelegateCommand), typeof(MapEventToCommandBase<TEventArgsType>), new PropertyMetadata(null, OnCommandPropertyChanged));
        public static readonly DependencyProperty CommandParameterProperty = DependencyProperty.Register("CommandParameter", typeof(object), typeof(MapEventToCommandBase<TEventArgsType>), new PropertyMetadata(null, OnCommandParameterPropertyChanged));

        private static void OnCommandParameterPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var invokeCommand = d as MapEventToCommand;
            if (invokeCommand != null)
            {
                invokeCommand.SetValue(CommandParameterProperty, e.NewValue);
            }
        }

        private static void OnCommandPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var invokeCommand = d as MapEventToCommand;
            if (invokeCommand != null)
            {
                invokeCommand.SetValue(CommandProperty, e.NewValue);
            }
        }

        protected override void Invoke(object parameter)
        {
            if (this.Command == null)
            {
                return;
            }

            if (this.Command.CanExecute(parameter))
            {
                var eventInfo = new EventInformation<TEventArgsType>
                                    {
                                        EventArgs = parameter as TEventArgsType,
                                        Sender = this.AssociatedObject,
                                        CommandArgument = GetValue(CommandParameterProperty)
                                    };
                this.Command.Execute(eventInfo);
            }
        }

        public IDelegateCommand Command
        {
            get
            {
                return (IDelegateCommand)base.GetValue(CommandProperty);
            }
            set
            {
                base.SetValue(CommandProperty, value);
            }
        }

        public object CommandParameter
        {
            get
            {
                return base.GetValue(CommandParameterProperty);
            }
            set
            {
                base.SetValue(CommandParameterProperty, value);
            }
        }
    }

Our MapEventToCommandBase class simply adds Command and CommandParameter DependencyProperties so we can set via DataBinding the command and (optionally) parameter for the event.
It has one type parameter TEventArgsType that it uses so it can send the appropriate EventArgs from the Event that occurred to the command we are calling.
That is why TEventArgsType has a constraint that it has to inherit from EventArgs since every UI event sends some information in a class that inherits from EventArgs or sends EventArgs.Empty.

The meat of this class is the method Invoke that overrides the method in its base class TriggerAction.
This method is called from the Silverlight runtime when some event occurs in the UI and the parameter sent is the instance of class that inherits from EventArgs and carries the information specific to that event (MouseEventArgs, DragEventArgs, KeybardEventArgs etc).

What we do in this method is that we take that event information we received and pack it into new class that we will send to our command.

Its this part of code:

            if (this.Command.CanExecute(parameter))
            {
                var eventInfo = new EventInformation<TEventArgsType>
                                    {
                                        EventArgs = parameter as TEventArgsType,
                                        Sender = this.AssociatedObject,
                                        CommandArgument = GetValue(CommandParameterProperty)
                                    };
                this.Command.Execute(eventInfo);
            }

So we construct the instance of generic EventInformation class of certain EventArgs inheritor type and we include there the sender of the event and the optional argument we sent from XAML binding.

Here is how the generic EventInformation class looks like:

    public class EventInformation<TEventArgsType> where TEventArgsType : EventArgs
    {
        public object Sender { get; set; }
        public TEventArgsType EventArgs { get; set; }
        public object CommandArgument { get; set; }
    }

It allows us to easily create strongly typed class for each of possible events that can occur in the UI.
For RoutedEvents like Loaded event the RoutedEventArgs will be passed there.

Lets continue. Since our MapEventToCommandBase is abstract and generic class we need to inherit it to be able to actually use it in Xaml so here are some examples of concrete MapSOMEKINDOFEventToCommand implementations:

First MapMouseEventToCommand:

    public class MapMouseEventToCommand : MapEventToCommandBase<MouseEventArgs>
    {

    }

So as you see there is nothing we need to implement here, just to specify the type of the event we want to handle.
If Xaml would support generics we could make the MapEventToCommandBase not to be abstract and use it directly but until Xaml learns to accept generics this is the best way i could figure out.

Then there is the MapKeyboardEventToCommand:

    public class MapKeyboardEventToCommand : MapEventToCommandBase<KeyEventArgs>
    {

    }

So we can do this for any type of event that we need (see the sample Visual Studio 2010 Project for more examples)

If we don’t need the specific EventArgs we can also use the MapEventToCommand class that uses EventArgs as its type so it can be used with ANY event.
The drawback is that in the command we will receive the EventInformation<EventArgs> so we need to cast the EventArgs property of that class to some specific EventArgs inheritor class so we lose type safety.

So now that all is in place lets see how we can use our new magic classes from Xaml in Views.

First the simplest event: Loaded.

In Xaml of our View we must place this code:

    <Interactivity:Interaction.Triggers>
        <Interactivity:EventTrigger EventName="Loaded">
            <TriggerActions:MapEventToCommand Command="{Binding Path=LoadedCommand}" CommandParameter="Shell view loaded at {0:d/M/yyyy HH:mm:ss:fff tt}" />
        </Interactivity:EventTrigger>
    </Interactivity:Interaction.Triggers>

So we are creating EventTrigger for event with name “Loaded” and for this event we are setting TriggerAction to our MapEventToCommand. This event will trigger when control is loaded and since we use DataBinding to set the Command property, when the event occurs, LoadedCommand on our DataContext will be invoked with the string parameter we hard coded in CommandParameter (we could used DataBinding there also but i skipped this for now to keep things simple).

Next, in our ViewModel we have to define the actual LoadedCommand command.

Important note: DO NOT FORGET to always use OnPropertyChanged in the command’s property setter if you want all of this to work properly:

        private ICommand loadedCommand;
        public ICommand LoadedCommand
        {
            get { return loadedCommand; }
            private set
            {
                loadedCommand = value;
                this.OnPropertyChanged("LoadedCommand");
            }
        }

Another note: we are defining our command as ICommand property and later we will set them with DelegateCommands instances but this is off course perfectly fine since DelegateCommand implements IDelegateCommand that implements ICommand interface.

And in the constructor of ViewModel with single lambda we added the actual code that will run when command is executed (we just set some string property called LoadedTime to the current DateTime formated by the format text given in the parameter).

Since the View is bound to this LoadedTime property it’s shown on the control when its changed, triggered by INotifyPropertyChanged:

        this.LoadedCommand
            = new DelegateCommand<EventInformation<EventArgs>>
                (p =>
                     {
                         LoadedTime = string.Format(p.CommandArgument.ToString(), DateTime.Now);
                     });

Lets see how we would map a MouseMove event:

    <Interactivity:Interaction.Triggers>

        <Interactivity:EventTrigger EventName="MouseMove">
            <TriggerActions:MapMouseEventToCommand Command="{Binding Path=ShowMousePositionCommand}" />
        </Interactivity:EventTrigger>

    </Interactivity:Interaction.Triggers>

So we are doing the same thing here only we are using MapMouseEventToCommand in stead of the basic MapEventToCommand – we are doing this so we get strongly typed MouseEventArgs from the original event passed as EventArgs parameter in the EventInformation class that will be passed to the command.

Here is the command definition from our ViewModel:

        private ICommand showMousePositionCommand;
        public ICommand ShowMousePositionCommand
        {
            get { return showMousePositionCommand; }
            set { showMousePositionCommand = value;
            this.OnPropertyChanged("ShowMousePositionCommand");

            }
        }

And here is part of the ViewModel constructor where we actually define the code triggered inside the command:

        this.ShowMousePositionCommand
            = new DelegateCommand<EventInformation<MouseEventArgs>>(
            p =>
            {
                this.MousePosition = string.Format("x:{0} y:{1}",
                    p.EventArgs.GetPosition(null).X, p.EventArgs.GetPosition(null).Y);
            });

What happens here is that when our command is invoked (this is triggered when user moves his mouse pointer in our View) we use the received MouseEventArgs (from EventArgs property) of the EventInformation instance to get the current mouse position and we create a string representation of it and we set a public property on our ViewModel.

And our View is again data-bound to this property – so it will get notification that its value has changed and re-display it on screen so we will have realtime coordinates of our mouse pointer displayed in the view as we move the pointer.

Check out the demo application to see this in action.

So we managed to wire up events from View to the ViewModel in Xaml via DataBinding.

Here is how our View’s backend code .cs file looks like:

using System.Windows.Controls;

namespace EventCommands.Views
{
    public partial class ShellView : UserControl
    {
        public ShellView()
        {
            InitializeComponent();
        }
    }
}

As you can see we added zero logic to our View – its only code generated by the Visual Studio when we created the UserControl for the, so its clean design, decoupled View from the ViewModel, and we can later change our Views and our ViewModels won’t event notice ;)

For those that do not have Silverlight 4 installed yet, here is the screen shot of the running demo application showing all the code we have written for this experiment:

If you run the application you will see two independent instances of the small sample EventsWidget for showing Events triggered on View.

Currently im demonstrating MouseMove event, DragAndDrop event, KeyDown event and also Loaded event.

Other UI events can be easily added and are completely supported by the given code.

I deliberately added two instances of same widget on the main page so its clear that data binding works independently and that each control can has its own ViewModel and DataBinds events to Commands in its own ViewModel.

In same way the main control (ShellView) has its own ViewModel and its own Events DataBound to commands in its own ViewModel etc.

You can download the sample application Visual Studio 2010 solution here.

Modal dialogs with MVVM and Silverlight 4

In the previous post we covered how to show Views and how to wire them up with their ViewModels while preserving ability to correctly see their preview in Visual Studio and Blend design mode.

In this post i would like to tackle another problem that is very common in MVVM and yet very rarely done correctly.

I will try to provide simple and platform agnostic way of showing Modal Dialogs in MVVM manner without any code in View (later in the post we will reuse same concept and provide way to show simple message dialogs in the same way).

For those of you that have no patience here is the demo application that shows dialogs in action. On the main page there are two identical views each of them showing a list of users. For each user if you click the Edit button you will see the modal dialog to edit users properties.
Del button shows the message dialog to confirm deleting of the user n or to cancel it.

So lets begin: Actual implementation of the concept will be done in Silverlight 4 but it can be easily and without any pain converted to any other UI platform like WPF etc.

Our main design goals are:

  1. Platform agnostic solution to show modal dialogs that could be easily reused in WPF (or any other platform that supports concept of dialogs)
  2. We want our modal dialogs to be triggered by some UI event in our Views (like click on the button etc) but not from codebehind of the view
  3. Actual logic of showing dialogs must reside in ViewModel and NEVER (oh never) in code behind of the dialog (View)
  4. Dialogs must support MVVM pattern themselves so they should be able to bind to their ViewModel if needed
  5. Dialogs should be able to return result to the caller (maybe we wont need this always but there must be a way if needed)

Nice thing that could help us a lot is that Silverlight 3/4 comes with very handy ChildWindow control that is perfect fit for what we are trying to do, so we will try to reuse it in smart way.

The question remains how to use Silverlight ChildWindow class with MVVM pattern and to remain decoupled from anything that is platform specific about it.

We will first take the most important things that each Modal Dialog should have and extract this to separate interface IModalWindow:

  public interface IModalWindow
  {
    bool? DialogResult { get; set; }
    event EventHandler Closed;
    void Show();
    object DataContext { get; set; }
    void Close();
  }

As you can see IModalWindow is almost like an 1:1 abstraction of ChildWindow class :)
But its important to note here that IModalWindow contains only pure .NET constructs so it does not have anything Silverlight specific so that means we can implement this interface and create modal dialog controls in any .NET platform (WPF, WinForms etc).

IModalWindow has Show and Close methods, then it has DataContext so we can bind it to its ViewModel, then there is DialogResult boolean property to tell us if user confirmed the action or not, and it has event handler so we can hook to it when dialog is closed to pickup some results or do other actions (if we need it).

In order to be able to actually show dialogs that implement IModalWindow to our user we will introduce another layer of abstraction – it will be service that implements IModalDialogService interface that will have generic methods for showing the dialogs and completely hide the details of the implementation – as we said this should be platform agnostic so interface will contain nothing specific to Silverlight.

here is how the IModalDialogService interface looks:

  public interface IModalDialogService
  {
    void ShowDialog<TViewModel>(IModalWindow view, TViewModel viewModel, Action<TViewModel> onDialogClose);

    void ShowDialog<TDialogViewModel>(IModalWindow view, TDialogViewModel viewModel);
  }

Our service interface defines two methods, first is one when when we want to specify OnClose handler so that we can do some action when dialog is closed and second overload is for showing modal dialogs in ‘Fire and forget’ mode without knowing when or how the dialog is closed.

Both ShowDialog methods are generic, accepting TViewModel type where we specify type of the ViewModel for our dialog (usually this is ViewModel interface). If we don’t need ViewModel for the dialog we can always set this to null.

So when showing dialog we pass the actual dialog – the View (i will explain later how we will get it) and its ViewModel and optionally we define an Action that is called when the dialog is closed (with the ViewModel instance of the dialog as the parameter – this is how we can get the results of the dialog or data user entered on the dialog etc).

And finally lets see how the Silverlight version of the ModalDialogService is implemented:

  public class ModalDialogService : IModalDialogService
  {
    public void ShowDialog<TDialogViewModel>(IModalWindow view, TDialogViewModel viewModel, Action<TDialogViewModel> onDialogClose)
    {
      view.DataContext = viewModel;
      if (onDialogClose != null)
      {
        view.Closed += (sender, e) => onDialogClose(viewModel);
      }
      view.Show();
    }

    public void ShowDialog<TDialogViewModel>(IModalWindow view, TDialogViewModel viewModel)
    {
      this.ShowDialog(view, viewModel, null);
    }
  }

Implementation as you can see is very simple.
Service just sets the passed ViewModel to the DataContext of the passed dialog view, attaches the OnClose handler if we provided it and finally shows the view.

Now lets see the XAML and codebehind of one simple dialog we defined in sample application – dialog to edit user detials:

<controls:ChildWindow x:Class="MvvmModalDialogs.Views.EditUserModalDialogView"
           xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
           xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
           xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
           xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d"
           xmlns:controls="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls" xmlns:DummyViewModels="clr-namespace:MvvmModalDialogs.ViewModels.DummyViewModels" Width="400" Height="300"
           Title="Edit User" d:DataContext="{Binding Source={StaticResource viewModel}}" >
    <controls:ChildWindow.Resources>
        <DummyViewModels:DummyEditUserModalDialogViewModel x:Key="viewModel" ></DummyViewModels:DummyEditUserModalDialogViewModel>
    </controls:ChildWindow.Resources>
  <Grid x:Name="LayoutRoot" Margin="2">
    <Grid.RowDefinitions>
      <RowDefinition />
      <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>

        <TextBlock Text="{Binding Path=User.FullName}" HorizontalAlignment="Center" VerticalAlignment="Center" />

        <StackPanel Orientation="Horizontal" Grid.Row="1" HorizontalAlignment="Right" VerticalAlignment="Center">
            <Button x:Name="CancelButton" Content="Cancel" Click="CancelButton_Click" Width="75" Height="23" HorizontalAlignment="Right" Margin="0,5,20,5"  />
            <Button x:Name="OKButton" Content="OK" Click="OKButton_Click" Width="75" Height="23" HorizontalAlignment="Right" Margin="0,5,20,5"  />
        </StackPanel>

        <Grid Height="142" HorizontalAlignment="Center" Margin="30,17,0,0" Name="grid1" VerticalAlignment="Center" Width="310">
            <Grid.RowDefinitions>
                <RowDefinition Height="32*" />
                <RowDefinition Height="33*" />
                <RowDefinition Height="32*" />

            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="84*" />
                <ColumnDefinition Width="31*" />
                <ColumnDefinition Width="195*" />
            </Grid.ColumnDefinitions>
            <TextBlock Grid.Row="0" Grid.Column="0" Height="23" HorizontalAlignment="Right"  Text="User Id:" VerticalAlignment="Center"  />
            <TextBlock Height="23" HorizontalAlignment="Stretch"  Text="{Binding User.Id}" VerticalAlignment="Center" Grid.Row="0" Grid.Column="2" />

            <TextBlock Grid.Row="1" Grid.Column="0" Height="23" HorizontalAlignment="Right"  Text="Username:" VerticalAlignment="Center"  />
            <TextBox Height="23" HorizontalAlignment="Stretch"  Text="{Binding User.Username, Mode=TwoWay}" VerticalAlignment="Center" Grid.Row="1" Grid.Column="2" />

            <TextBlock Grid.Row="2" Grid.Column="0" Height="23" HorizontalAlignment="Right"  Text="Is Admin:" VerticalAlignment="Center"  />
            <CheckBox Height="23" HorizontalAlignment="Stretch" IsChecked="{Binding User.IsAdmin, Mode=TwoWay}" VerticalAlignment="Center" Grid.Row="2" Grid.Column="2" />

        </Grid>
    </Grid>
</controls:ChildWindow>

So its just simple ChildWindow control, that has few TextBoxes to show and edit details of one User instance.

And in the codebehind of the ChildWindow control we just mark it as implementor of our IChildWindow interface (and we set the DialogResult to true if user clicked OK button, but this can be done in ‘pure’ way via DelegateCommand i just used codebehind here for simplicity and because its not part of the business logic, its concern of the UI to tell us if the user closed dialog by clicking on OK button or not).

    public partial class EditUserModalDialogView : IModalWindow
    {
        public EditUserModalDialogView()
        {
            InitializeComponent();
        }

        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = true;
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }
    }
 

So all this gives us a completely platform agnostic solution to modal dialogs, and yet we used the powerful ChildWindow control that comes with Silverlight.
If we later decide to implement our modal dialogs in a different way we can do this easily just by creating a different control that implements IChildWindow and we are cool, nothing needs to be changed in our code that shows the dialogs.

So now how would we use this dialog in code?

There is one more peace of the puzzle to solve. We need to register our dialog controls somehow so we can easily pass them to our IModalService to show them so i will use ServiceLocator pattern for this.

We will create a Bootstrapper class that will be called in App.xaml.cs on application startup and this class will have task to register all common dialogs that we will be using in our application:

public class Bootstrapper
    {
        public static void InitializeIoc()
        {
            SimpleServiceLocator.SetServiceLocatorProvider(new UnityServiceLocator());
            SimpleServiceLocator.Instance.Register<IModalDialogService, ModalDialogService>();
            SimpleServiceLocator.Instance.Register<IMessageBoxService, MessageBoxService>();
            SimpleServiceLocator.Instance.Register<IMainPageViewModel, MainPageViewModel>();

            SimpleServiceLocator.Instance.Register<IModalWindow, EditUserModalDialogView>(Constants.EditUserModalDialog);
        }
    }

As you can see we are registering (among other things) EditUserModalDialogView that is in fact ChildWindow control as implementor of IModalWindow interface under a name from constants (Constants is the class holding distinct string names for each of the dialog types we want to use in application).

So now that everything is set, and our ServiceLocator knows of our dialogs, we can retrieve new instance of any of our dialogs to show them from the ViewModel of some view (when some button is clicked inside a DelegateCommand etc).

In this example i have only one dialog type that is implementing IModalWindow interface – EditUserModalDialogView, but i could have had many different types of dialogs that i will be showing to users so i would register them all in the Boostrapper as implementors of IModalWindow but under different named constants.
Then i would just retrieve the one i need by asking my service locator for a type that implements IModalWindow and supplying a string key that would determine which dialog exactly i need.

For example to retrieve instance of EditUserModalDialogView i would type this:

var dialog = SimpleServiceLocator.Instance.Get<IModalWindow>(Constants.EditUserModalDialog);

In order to just show dialog without any ViewModel or OnClose callback i would do this:

var dialog = SimpleServiceLocator.Instance.Get<IModalWindow>(Constants.EditUserModalDialog);
this.modalDialogService.ShowDialog(dialog, null);

or to set ViewModel for the dialog i could do this:

var dialog = SimpleServiceLocator.Instance.Get<IModalWindow>(Constants.EditUserModalDialog);
this.modalDialogService.ShowDialog(dialog, new EditUserModalDialogViewModel
{
User = userInstanceToEdit
});

These were all simple cases. Now lets see how we can show dialog from DelegateCommand in ViewModal when user clicks on some Button in View, and also let’s set a callback function to be called when dialog is closed so we can do something meaningful like updating user details:

First we crate button on View to trigger the action and bind its Command property to a DelegateCommand in ViewModel and use binding for CommandParameter (in this case binding is the actual User instance):

<Button Content="Edit" Command="{Binding Source={StaticResource viewModelLocator}, Path=ViewModel.ShowUserCommand}" CommandParameter="{Binding}" />

And now in the ViewModel in the ShowUserCommand DelegateCommand we place the code to show the dialog and update Users collection afterwards if needed:

        this.ShowUserCommand = new DelegateCommand<User>(userInstanceToEdit =>
        {
          var dialog = SimpleServiceLocator.Instance.Get<IModalWindow>(Constants.EditUserModalDialog);
          this.modalDialogService.ShowDialog(dialog, new EditUserModalDialogViewModel
          {
            User = userInstanceToEdit
          },
          returnedViewModelInstance =>
          {
            if (dialog.DialogResult.HasValue && dialog.DialogResult.Value)
            {
            var oldPos = this.Users.IndexOf(userInstanceToEdit);
            this.Users.RemoveAt(oldPos);
            this.Users.Insert(oldPos, returnedViewModelInstance.User);
            }
            });
        });

So basically im setting the DelegateCommand (see details of the DelegateCommand implementation in the project attached to the post) with code to retrieve the Edit User dialog from the ServiceLocator.
Then im calling services ShowDialog method, passing the new instance of EditUserModalDialogViewModel as the ViewModel of the dialog (containing the user instance i want to edit) and im passing lamda for onDialogClose callback to remove old instance of the User from Users collection on ViewModel and replace it with the new one we received from the dialog.
Off course im first checking if user clicked on Ok button (using dialog.DialogResult property to check that).

And there you have it: simple MVVM solution for modal dialogs that you can port to any platform and implement with any kind of control or popup you want.

To show this concept in more detail i created another similar service to show message boxes to the user.
Again we have the service interface – IMessageBoxService that offers two ways of showing message boxes, first one more complex where we specify message, caption and buttons displayed on the message box and second one, simpler where we just specify message and caption, so only OK button is shown to the user:

  public interface IMessageBoxService
  {
    GenericMessageBoxResult Show(string message, string caption, GenericMessageBoxButton buttons);
    void Show(string message, string caption);
  }

I also created abstractions for the common button types and return results so we don’t depend on Silverlight MessageBox class (that we will use underneath) is using:

  public enum GenericMessageBoxButton
  {
    Ok,
    OkCancel
  }

  public enum GenericMessageBoxResult
  {
    Ok,
    Cancel
  }

So lets see how the actual Silverlight implementation of IMessageBoxService interface would look like:

  public class MessageBoxService : IMessageBoxService
  {
    public GenericMessageBoxResult Show(string message, string caption, GenericMessageBoxButton buttons)
    {
      var slButtons = buttons == GenericMessageBoxButton.Ok
                        ? MessageBoxButton.OK
                        : MessageBoxButton.OKCancel;

      var result = MessageBox.Show(message, caption, slButtons);

      return result == MessageBoxResult.OK ? GenericMessageBoxResult.Ok : GenericMessageBoxResult.Cancel;
    }

      public void Show(string message, string caption)
      {
          MessageBox.Show(message, caption, MessageBoxButton.OK);
      }
  }

Again its very simple, we are using the built in Silverlight’s MessageBox class to show the actual message box but later we can decide its not good enough and implement it in another way (maybe with 3rd party message box component etc) yet our code in ViewModel wont change since it will be talking only to our interface.

Here is the example of how i use this MessageBoxService in the demo project for this post:

        this.DeleteUserCommand = new DelegateCommand<User>(p =>
        {
          var result = this.messageBoxService.Show(string.Format("Are you sure you want to delete user {0} ???", p.Username),
              "Please Confirm", GenericMessageBoxButton.OkCancel);
          if (result == GenericMessageBoxResult.Ok)
          {
            this.Users.Remove(p);
          }
        });

What i do here is just set the DelegateCommand in ViewModel to first show the message box with Ok and Cancel buttons and if user pressed Ok do some action – delete from the list.

So i think this two solutions covered all design goals we set on the start: we have decoupled way of showing modal dialogs and message boxes currently done in Silverlight but they could be easily converted to another platform.
Also approach is MVVM friendly without any hacks so any pattern purist can be satisfied with it.
If you have some concerns or suggestions on this approach i would be happy to hear it!

Here is the attached VS 2010 solution with full source code from the post.
Live demo of the application showing modal dialogs and message boxes flying around the screen.

Wiring up View and Viewmodel in MVVM and Silverlight 4 – Blendability included

Im a BIG fan of  Silverlight and also i really like the Model View ViewModel pattern. Nice part is that those two fit perfectly. The downside is that everyone is doing MVVM the way they like it or the way they think they like it. There is no strict guidance,  there are no ‘Bible’ kind of books written on the subject, there is only a enormous pile of information (of varying quality) on the web contributed by developers all over the world trying to (ab)use this pattern in their everyday practice.

(probably you can take this post as just another small contribution to that information pile on the MVVM).

Yes, there are many mature MVVM frameworks for Silverlight and WPF out there (Prism, MVVMLight, Caliburn etc) and they try to provide standardized ways of doing things but they either lack features or they are overly complex for my taste. Also problem with frameworks is that each of them solves some problems in good or excellent way yet other things are not covered or they are done in way that is not acceptable for each need.

So i guess if you could just merge them all to one solid framework it would be a hell of a tool.

One of the features that most of Silverlight MVVM frameworks are actively trying to solve is the process of wiring up Views and Viewmodels and related to this problem is so-called Blendability.  Blendability is just a fancy word for enabling designers to see the correct preview of their Views in Visual Studio and/or Expression Blend.

And this is not easy task that’s for sure.  Here is why:

As soon as your View Models become more complex and if you start using Dependency Injection with Constructor Injection – because IDE is trying to instantiate your ViewModel in designtime and fails – design surface will blow up in your face and instead of the preview you will just see some error message (if you are lucky enough and your IDE did not crashed already).

I do like how MVVMLight framework is preserving Blendability by using concept of the ViewModelLocator.

Basically this class is some sort of ViewModel factory that returns different ViewModel if its called in runtime or designtime. This keeps the IDE happy and it does not crash because it gets some dummy model when in designtime and when application is trully running it then gets realt ViewModel so everyone is happy :)

While this is pretty smart concept, i don’t like how it is implemented in practice.

In MVVMLight ViewModelLocator  is usaully defined in App.Xaml.cs as global resource (and therefore created on application startup).

Also designtime and runtime versions of ViewModel instances in ViewModelClass are defined as static properties and therefore also created when ViewModelLocator class is first used. Also those static ViewModels are then shared between multiple views which is in my opinion simply  wrong.

Every view should have its own ViewModel instance created for it in runtime.

For example what if i want to show same view multiple times on a single page? (lets say its case of multiple RSS feed widgets on one page each of them showing different RSS feed etc).

Each ViewModel should be instantiated at the same time as its View or at least i should have the freedom to choose when its created depending on the situation and also i should be able to choose if it is shared between multiple instances of same view or not.

So inspired by the concept of ViewModelLocator from MVVMLight i created my own variation of this class and i will be presenting this solution in this post.

So enough talk  lets first show some code. This is my current version of the ViewModelLocatorBase class:

ViewModelLocatorBase.cs:

using System.ComponentModel;
using Framework.Abstractions.Silverlight.ServiceLocation;

namespace Framework.Implementors.Silverlight.MVVM
{
  public abstract class ViewModelLocatorBase<TViewModel> : NotifyPropertyChangedEnabledBase where TViewModel : class
  {
    private static bool? isInDesignMode;
    private TViewModel runtimeViewModel;
    private TViewModel designtimeViewModel;

    /// <summary>
    /// Gets a value indicating whether the control is in design mode
    /// (running in Blend or Visual Studio).
    /// </summary>
    public static bool IsInDesignMode
    {
      get
      {
        if (!isInDesignMode.HasValue)
        {
          isInDesignMode = DesignerProperties.IsInDesignTool;
        }

        return isInDesignMode.Value;
      }
    }

    /// <summary>
    /// Holds the intance of the runtime version of the ViewModel that is instantiated only when application is really running by retrieving the instance from IOC container
    /// </summary>
    protected TViewModel RuntimeViewModel
    {
      get
      {
        if (this.runtimeViewModel == null)
        {
          this.RuntimeViewModel = SimpleServiceLocator.Instance.Get<TViewModel>();
        }
        return runtimeViewModel;
      }

      set
      {
        runtimeViewModel = value;
        this.OnPropertyChanged("ViewModel");
      }
    }

    /// <summary>
    /// Gets current ViewModel instance so if we are in designer its <see cref="DesigntimeViewModel"/> and if its runtime then its <see cref="RuntimeViewModel"/>.
    /// </summary>
    public TViewModel ViewModel
    {
      get
      {
        return IsInDesignMode ? this.DesigntimeViewModel : this.RuntimeViewModel;
      }
    }

    /// <summary>
    /// Holds the intance of the designtime version of the ViewModel that is instantiated only when application is opened in IDE designer (VisualStudio, Blend etc).
    /// </summary>
    public TViewModel DesigntimeViewModel
    {
      get
      {
        return designtimeViewModel;
      }

      set
      {
        designtimeViewModel = value;
        this.OnPropertyChanged("ViewModel");
      }
    }
  }
}

As you can see ViewModelLocatorBase is generic and abstract class that should be inherited by concrete ViewModelLocators, usually one for each View but this is not necessarily the case and you can have as many ViewModel locators for single view as you like (or you can share same ViewModelLocator between multiple instances of same View on one page if that is really what you need, also each view can have its own if needed).

Generic type TViewModel is usually the interface that your ViewModel is implementing (you could use concrete class type there but i strongly disagree with that – Views should bind to interfaces and later you can easily mock them etc).
ViewModelLocatorBase inside its static property IsInDesignMode determines if its instantiated inside aome IDE designer or inside the real running application.

I have tested it in Blend 3 and Visual Studio 2010 Beta 2 and it works fine.

Based on that fact (runtime or designtime) ViewModelLocatorBase.ViewModel property returns appropriate ViewModel instance.
If its designtime it returns value of DesignTimeViewModel property and if its runtime it returns RuntimeViewModel property value.
Now as you can see in the getter of RuntimeViewModel property, when its first time accessed it retrieves the concrete instance of our generic TViewModel type (it uses my home grown IOC adapter called SimpleServiceLocator but you can plugin any IOC you want behind it).

This instance is then saved to private property so its created only once.

So this way on runtime you will get there whichever concrete implementation you set up in your IOC for the TViewModel type.

Here is how i setup IOC in Bootstrapper class:

  public class Bootstrapper
  {
    public static void InitializeIoc()
    {
      SimpleServiceLocator.SetServiceLocatorProvider(new UnityServiceLocator());
      SimpleServiceLocator.Instance.Register<IMessageBoxService, MessageBoxService>();
      SimpleServiceLocator.Instance.Register<IEditUsersViewModel, EditUsersViewModel>();
    }
  }

To have something returned from the getter of the ViewModel in designtime we need to set the DesigntimeViewModel property.
We do that in the concrete ViewModelLocator class that is inheriting from ViewModelLocatorBase so that in design time IDE will get this instance.

Here is one simple concrete ViewModelLocator implementation:

  public class EditUsersViewModelLocator : ViewModelLocatorBase<IEditUsersViewModel>
  {
    public EditUsersViewModelLocator()
    {
      this.DesigntimeViewModel = new DummyEditUsersViewModel();
    }
  }

So the concrete EditUsersViewModelLocator class simply inherits the ViewModelLocatorBase and for the generic type it specifies the interface IEditUsersViewModel that ViewModels for the EditUsersView should implement and after this it sets the value of the DesigntimeViewModel property to a instance of DummyEditUsersViewModel which is a (as its name clearly states) just some dummy implementation of the IEditUsersViewModel with some test data to be displayed on the screen when editing this view in Blend or VisualStudio designer.

Sounds simple? well that was the original goal :)

Lets paste some more code. This is how the IEditUsersViewModel interface looks like:

  public interface IEditUsersViewModel
  {
    ObservableCollection<User> Users { get; }
    ICommand DeleteUserCommand { get; }
  }

Here is the dummy ViewModel for the design time that has test data to be displayed in designtime:
(it uses static properties to prevent VS2010 with r# from crashing if you open the views without first compiling the whole solution)

  public class DummyEditUsersViewModel : ViewModel, IEditUsersViewModel
  {
    private static ObservableCollection<User> users = new ObservableCollection<User>();

    static DummyEditUsersViewModel()
    {
      users = new ObservableCollection<User>
                     {
                       new User {Username = "Designtime User a", IsAdmin = true},
                       new User {Username = "Designtime User b", IsAdmin = true},
                       new User {Username = "Designtime Admin User c", IsAdmin = true},
                       new User {Username = "Designtime Admin User d", IsAdmin = true}
                     };
       deleteUserCommand = new DelegateCommand<object>(p => {});
    }

      private static ICommand deleteUserCommand;
      public ICommand DeleteUserCommand
      {
          get { return deleteUserCommand; }
          private set { deleteUserCommand = value; }
      }

      public ObservableCollection<User> Users
    {
      get { return users; }
      set { users = value;}
    }
  }

And here is how we would use this concrete ViewModelLocator in our view:

<UserControl x:Class="MvvmBlendability.Views.EditUsersView"
    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" xmlns:ViewModels="clr-namespace:MvvmBlendability.ViewModels" mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400"  d:DataContext="{Binding Source={StaticResource viewModelLocator}, Path=ViewModel}"  >
    <UserControl.Resources>
        <ViewModels:EditUsersViewModelLocator x:Key="viewModelLocator"  />
    </UserControl.Resources>

    <UserControl.DataContext>
        <Binding Source="{StaticResource viewModelLocator}" Path="ViewModel" />
    </UserControl.DataContext>

    <Grid x:Name="LayoutRoot" Background="Silver" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="10">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"></RowDefinition>

            <RowDefinition Height="*"></RowDefinition>
        </Grid.RowDefinitions>
        <TextBlock HorizontalAlignment="Right" Text="Edit Users"  FontSize="18" Margin="0,10,10,5" FontFamily="Arial Black" />
        <ListBox Grid.Row="1" ItemsSource="{Binding Path=Users}" Background="AliceBlue" HorizontalAlignment="Stretch" >

            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition MinWidth="300"></ColumnDefinition>
                            <ColumnDefinition Width="21*"></ColumnDefinition>
                            <ColumnDefinition Width="21*"></ColumnDefinition>
                        </Grid.ColumnDefinitions>
                        <TextBlock Text="{Binding Path=Username}" />
                        <Button Grid.Column="2" Content="Del" Command="{Binding Source={StaticResource viewModelLocator}, Path=ViewModel.DeleteUserCommand}" CommandParameter="{Binding}" />

                    </Grid>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>

</UserControl>

In the Xaml its very important that you notice this part of the code in the UserControl definition:

d:DataContext="{Binding Source={StaticResource viewModelLocator}, Path=ViewModel}"

Its the very important part and if you miss this out you will not see much in the designer. This actually tells the designer what to use as DataContext of the UserControl (this is our view) in designtime and we will point it to the ViewModel property of our ViewModelLocator instance we defined in the UserControl.Resources section on top of the view.

Yet this code sets the DataContext binding for view for runtime:

    <UserControl.Resources>
        <ViewModels:EditUsersViewModelLocator x:Key="viewModelLocator"  />
    </UserControl.Resources>

    <UserControl.DataContext>
        <Binding Source="{StaticResource viewModelLocator}" Path="ViewModel" />
    </UserControl.DataContext>

We first create instance of out ViewModelLocator in resources of the UserControl (View) and then we set this as DataContext.
And in the design time in VisualStudio when we open EditUsersView we will get this:

As you can see design surface is working and we can see our View showing data from our  DummyEditUsersViewModel.

I have created one more View called ShellView and placed in its Xaml two instances of EditUsersView so that we can be sure it will work in this scenario also.

As i mentioned each instance of the view will get its own ViewModel created and wired up (in this case since its designtime each view will get its own instance of designtime view mode – DummyEditUsersViewModel).

First lets look at the xaml of the ShellView:

<UserControl x:Class="MvvmBlendability.Views.ShellView"
    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" xmlns:Views="clr-namespace:MvvmBlendability.Views" mc:Ignorable="d"
    d:DesignHeight="400" d:DesignWidth="400">

    <Grid x:Name="LayoutRoot" Background="White">
        <Grid.RowDefinitions>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
        </Grid.RowDefinitions>
        <Views:EditUsersView Grid.Row="0" />
        <Views:EditUsersView Grid.Row="1" />
    </Grid>
</UserControl>

In the ShellView we have two instances of the EditUsersView and both of  them will be assigned with separate ViewModel instance as we declared it in the Xaml of those views via ViewModelLocator so we dont need any ViewModelLocator for ShellView.

Basically EditUsersViews are here used as a component that we dropped on another view and this component takes care of its own DataContext without having to worry about it again. Off course we could also create view that does not have ViewModel assigned via ViewModel locator and place it on ShellView and set its DataContext directly via DataBinding.

All possibilities  are there we just need to choose the appropriate one.

So lets see how ShellView looks in the VS2010 Beta 2 designer:

And its working in Blend also (but be sure to use Microsoft Expression Blend Preview for .NET 4 version to be able to open this solution. Its not working in plain Blend 3 because this version is not supporting VS 2010 projects/solutions).

So here is the ShellView in Blend:

On the other hand, when we actually run our application in browser then ViewModelLocator sets ViewModel property to the real ViewModel instance (runtime version) and view is populated with real data from EditUsersViewModel just as we would expect:
Here is how it looks when we start our application in the browser:

As you can see each instance of the View has different data shown that proves that each has different instance of ViewModel set to its DataContext.

So we have accomplished our three main design goals:

  1. Simple yet powerful View to ViewModel wireup
  2. Blendability
  3. simplicity :)

Im attaching the VisualStudio 2010 solution with full source code of project used in this post.
You can see the live demo of this app here.

Hopefully this has given you some ideas on how to start with MVVM without having to learn frameworks before you event start programming. Later when you realize that you cannot accomplish all your ideas you can always switch to some framework and use it.

Unitl then: Happy DataBinding!