Click here to Skip to main content
13,192,855 members (55,478 online)
Click here to Skip to main content
Add your own
alternative version


124 bookmarked
Posted 19 May 2010

A Sample Silverlight 4 Application Using MEF, MVVM, and WCF RIA Services - Part 2

, 8 Jul 2011
Rate this:
Please Sign up or sign in to vote.
Part 2 of a series describing the creation of a Silverlight business application using MEF, MVVM Light, and WCF RIA Services. In this second part, we will go through various topics on how MVVM Light Toolkit is used in our sample application.
  • Download source files and setup package from Part 1

Article Series

This article is part two of a series on developing a Silverlight business application using MEF, MVVM Light, and WCF RIA Services.



In this second part, we will go through various topics on how the MVVM Light Toolkit is used in our sample application. I chose this toolkit mainly because it is lightweight. Also, it is one of the most popular MVVM frameworks supporting Silverlight 4.


One of the new features in Silverlight 4 is a pair of properties added to the ButtonBase class named Command and CommandParameter. This commanding infrastructure makes MVVM implementations a lot easier in Silverlight. Let's take a look at how RelayCommand is used for the "Delete User" button from the User Maintenance screen. First, we define the XAML code of the button as follows:

<Button Grid.Row="2" Grid.Column="0"

        VerticalAlignment="Top" HorizontalAlignment="Right" 

        Width="75" Height="23" Margin="0,5,167,5" 

        Content="Delete User"

        Command="{Binding Path=RemoveUserCommand}"

        CommandParameter="{Binding SelectedItem, ElementName=comboBox_UserName, 

The code above specifies that we should call the RemoveUserCommand defined in UserMaintenanceViewModel.cs and pass in a parameter of the currently selected user when the "Delete User" button is clicked. And, the RelayCommand RemoveUserCommand is defined as:

private RelayCommand<User> _removeUserCommand = null;

public RelayCommand<User> RemoveUserCommand
        if (_removeUserCommand == null)
            _removeUserCommand = new RelayCommand<User>(
                g => (issueVisionModel != null) && 
                       !(issueVisionModel.HasChanges) && (g != null));
        return _removeUserCommand;

private void OnRemoveUserCommand(User g)
        if (!_issueVisionModel.IsBusy)
            // cancel any changes before deleting a user
            if (_issueVisionModel.HasChanges)

            // ask to confirm deleting the current user
            var dialogMessage = new DialogMessage(
                s =>
                    if (s == MessageBoxResult.OK)
                        // if confirmed, removing CurrentUser

                        // cache the current user name as empty string
                        _userNameToDisplay = string.Empty;

                        _operation = UserMaintenanceOperation.Delete;
                        IsUpdateUser = true;
                        IsAddUser = false;

                Button = MessageBoxButton.OKCancel,
                Caption = Resources.ConfirmMessageBoxCaption

    catch (Exception ex)
        // notify user if there is any error

The code snippet above, when called, will first display a message asking to confirm whether to delete the selected user or not. If confirmed, the functions RemoveUser() and SaveChangesAsync(), both defined in the IssueVisionModel class, will get called, thus removing the selected user from the database.

The second parameter of the RelayCommand is the CanExecute method. In the sample code above, it is defined as "

g => (_issueVisionModel != null) && 
!(_issueVisionModel.HasChanges) && (g != null)
", which means that the "Delete User" button is only enabled when there are no pending changes and the selected user is not null. Unlike WPF, this CanExecute method is not automatically polled in Silverlight when the HasChanges property changes, and we need to call the RaiseCanExecuteChanged method manually, like the following:

private void _issueVisionModel_PropertyChanged(object sender, 
             PropertyChangedEventArgs e)
    if (e.PropertyName.Equals("HasChanges"))


The Messenger class from MVVM Light Toolkit uses a simple Publish/Subscribe model to allow loosely coupled messaging. This facilitates communication between the different ViewModel classes as well as communication from the ViewModel class to the View class. In our sample, we define a static class called AppMessages that encapsulates all the messages used in this application.

/// <summary>
/// class that defines all messages used in this application
/// </summary>
public static class AppMessages

    public static class ChangeScreenMessage
        public static void Send(string screenName)
            Messenger.Default.Send(screenName, MessageTypes.ChangeScreen);

        public static void Register(object recipient, Action<string> action)
                      MessageTypes.ChangeScreen, action);

    public static class RaiseErrorMessage
        public static void Send(Exception ex)
            Messenger.Default.Send(ex, MessageTypes.RaiseError);

        public static void Register(object recipient, Action<Exception> action)
                      MessageTypes.RaiseError, action);

    public static class PleaseConfirmMessage
        public static void Send(DialogMessage dialogMessage)

        public static void Register(object recipient, Action<DialogMessage> action)
                      MessageTypes.PleaseConfirm, action);

    public static class StatusUpdateMessage
        public static void Send(DialogMessage dialogMessage)

        public static void Register(object recipient, Action<DialogMessage> action)
                      MessageTypes.StatusUpdate, action);


In the code-behind file MainPage.xaml.cs, four AppMessages are registered. ChangeScreenMessage is registered to handle requests from the menu for switching between different screens. The other three AppMessages are all system-wide messages:

  • RaiseErrorMessage will display an error message if something goes wrong, and immediately logs off from the database.
  • PleaseConfirmMessage is used to display a message asking for user confirmation, and processes the call back based on user feedback.
  • StatusUpdateMessage is used to update the user on certain status changes, like a new issue has been successfully created and saved, etc.

Here is how we register the StatusUpdateMessage:

public MainPage()

    // register for StatusUpdateMessage
    AppMessages.StatusUpdateMessage.Register(this, OnStatusUpdateMessage);

#region "StatusUpdateMessage"

private static void OnStatusUpdateMessage(DialogMessage dialogMessage)
    if (dialogMessage != null)
        MessageBoxResult result = MessageBox.Show(dialogMessage.Content,
            dialogMessage.Caption, dialogMessage.Button);


#endregion "StatusUpdateMessage"

And, here is how we can send a message to the StatusUpdateMessage:

// notify user of the new issue ID
var dialogMessage = new DialogMessage(
         Resources.NewIssueCreatedText + addedIssue.IssueID,
    Button = MessageBoxButton.OK,
    Caption = Resources.NewIssueCreatedCaption



EventToCommand is a Blend behavior that is added as a new feature in the MVVM Light Toolkit V3, and is used to bind an event to an ICommand directly in XAML, which gives us the power to handle pretty much any event with RelayCommand from the ViewModel class.

Following is an example of how drag and drop of files is implemented in the "New Issue" screen. Let's check the XAML code first:

<ListBox x:Name="listBox_Files" Grid.Row="1" Grid.Column="0"


         ItemsSource="{Binding Path=CurrentIssue.Files, ValidatesOnNotifyDataErrors=False}">
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding Path=FileName, ValidatesOnNotifyDataErrors=False}" />
                <TextBlock Text="{Binding Path=Data.Length, StringFormat=' - \{0:F0\} bytes',
                                  ValidatesOnNotifyDataErrors=False}" />
        <i:EventTrigger EventName="Drop">
            <cmd:EventToCommand PassEventArgsToCommand="True"

                    Command="{Binding Path=HandleDropCommand, Mode=OneWay}" />

The code above basically specifies that the ListBox allows drag-and-drop, and when a Drop event fires, the HandleDropCommand from the IssueEditorViewModel class gets called. Next, let's look at how HandleDropCommand is implemented:

private RelayCommand<DragEventArgs> _handleDropCommand = null;

public RelayCommand<DragEventArgs> HandleDropCommand
        if (_handleDropCommand == null)
            _handleDropCommand = new RelayCommand<DragEventArgs>(
                e => CurrentIssue != null);
        return _handleDropCommand;

private void OnHandleDropCommand(DragEventArgs e)
        // get a list of files as FileInfo objects
        var files = e.Data.GetData(DataFormats.FileDrop) as FileInfo[];

        if (files != null)
            // loop through the list and read each file
            foreach (var file in files)
                using (var fs = file.OpenRead())
                using (MemoryStream ms = new MemoryStream())
                    // and then add each file into the Files entity collection
                        new Data.Web.File()
                            FileID = Guid.NewGuid(),
                            IssueID = CurrentIssue.IssueID,
                            FileName = file.Name,
                            Data = ms.GetBuffer()
    catch (Exception ex)
        // notify user if there is any error

HandleDropCommand will loop through the list of files dropped by the user, reads the content of each file, and then adds them into the Files EntityCollection. The data will later be saved to the database when the user saves the changes.

ICleanup Interface

Whenever the user chooses a different screen from the menu, a ChangeScreenMessage is sent, which eventually calls the following OnChangeScreenMessage method:

private void OnChangeScreenMessage(string changeScreen)
    // call Cleanup() on the current screen before switching
    var currentScreen = mainPageContent.Content as ICleanup;
    if (currentScreen != null)

    // reset noErrorMessage
    _noErrorMessage = true;

    switch (changeScreen)
        case ViewTypes.HomeView:
            mainPageContent.Content = new Home();
        case ViewTypes.NewIssueView:
            mainPageContent.Content = new NewIssue();
        case ViewTypes.AllIssuesView:
            mainPageContent.Content = new AllIssues();
        case ViewTypes.MyIssuesView:
            mainPageContent.Content = new MyIssues();
        case ViewTypes.BugReportView:
            mainPageContent.Content = new Reports();
        case ViewTypes.MyProfileView:
            mainPageContent.Content = new MyProfile();
        case ViewTypes.UserMaintenanceView:
            mainPageContent.Content = new UserMaintenance();
            throw new NotImplementedException();

From the code above, we can see that every time we switch to a new screen, the current screen is first being tested to see whether it supports the ICleanup interface. If it is, the Cleanup() method is called before switching to the new screen. In fact, any screen, except the Home screen which does not bind to any ViewModel class, implements the ICleanup interface.

The Cleanup() method defined in any of the View classes will first call the Cleanup() method on its ViewModel class to unregister any event handlers and AppMessages. Next, it will unregister any AppMessages used by the View class itself, and the last step is to release the ViewModel class by calling ReleaseExport<ViewModelBase>(_viewModelExport), thus making sure that there are no memory leaks. Let's look at an example:

public partial class Reports : UserControl, ICleanup
    #region "Private Data Members"
    private const double MinimumWidth = 640;
    private Lazy<ViewModelBase> _viewModelExport;
    #endregion "Private Data Members"

    #region "Constructor"
    public Reports()
        // initialize the UserControl Width & Height
        Content_Resized(this, null);

        // register for GetChartsMessage
        AppMessages.GetChartsMessage.Register(this, OnGetChartsMessage);

        if (!ViewModelBase.IsInDesignModeStatic)
            // Use MEF To load the View Model
            _viewModelExport = App.Container.GetExport<ViewModelBase>(
            if (_viewModelExport != null) DataContext = _viewModelExport.Value;
    #endregion "Constructor"

    #region "ICleanup interface implementation"

    public void Cleanup()
        // call Cleanup on its ViewModel
        // cleanup itself
        // set DataContext to null and call ReleaseExport()
        DataContext = null;
        _viewModelExport = null;

    #endregion "ICleanup interface implementation"


And here is the Cleanup() method in its ViewModel class:

#region "ICleanup interface implementation"
public override void Cleanup()
    if (_issueVisionModel != null)
        // unregister all events
        _issueVisionModel.GetAllUnresolvedIssuesComplete -= 
        _issueVisionModel.GetActiveBugCountByMonthComplete -= 
        _issueVisionModel.GetResolvedBugCountByMonthComplete -= 
        _issueVisionModel.GetActiveBugCountByPriorityComplete -= 
        _issueVisionModel.PropertyChanged -= 
        _issueVisionModel = null;
    // set properties back to null
    AllIssues = null;
    ActiveBugCountByMonth = null;
    ResolvedBugCountByMonth = null;
    ActiveBugCountByPriority = null;
    // unregister any messages for this ViewModel
#endregion "ICleanup interface implementation"

Next Steps

In this article, we visited the topics of how the MVVM Light toolkit is used: namely, RelayCommand, Messenger, EventToCommand, and ICleanup. In our last part, we will focus on how custom authentication, reset password, and user maintenance are done through WCF RIA Services.

I hope you find this article useful, and please rate and/or leave feedback below. Thank you!


  • May 2010 - Initial release
  • July 2010 - Minor update based on feedback
  • November 2010 - Update to support VS2010 Express Edition
  • February 2011 - Update to fix multiple bugs including memory leak issues
  • July 2011 - Update to fix multiple bugs


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Weidong Shen
Software Developer (Senior)
United States United States
Weidong has been an information system professional since 1990. He has a Master's degree in Computer Science, and is currently a MCSD .NET

You may also be interested in...

Comments and Discussions

QuestionWhat a great article Pin
essdataylor30-Aug-12 8:57
memberessdataylor30-Aug-12 8:57 
AnswerRe: What a great article Pin
Weidong Shen30-Aug-12 14:21
memberWeidong Shen30-Aug-12 14:21 
GeneralMy vote of 4 Pin
Edgars Palacis5-Jul-12 9:59
memberEdgars Palacis5-Jul-12 9:59 
GeneralThis article is a Fraud (please read on)... Pin
remesqny3-Jan-11 10:33
memberremesqny3-Jan-11 10:33 
GeneralRe: This article is a Fraud (please read on)... [modified] Pin
Julien Villers5-Aug-11 5:01
memberJulien Villers5-Aug-11 5:01 
QuestionHow do you add new views (User Control) Pin
remesqny30-Dec-10 14:25
memberremesqny30-Dec-10 14:25 
AnswerRe: How do you add new views (User Control) Pin
Weidong Shen30-Dec-10 17:57
memberWeidong Shen30-Dec-10 17:57 
AnswerRe: How do you add new views (User Control) Pin
Drammy5-Jan-11 3:44
memberDrammy5-Jan-11 3:44 

The NotImplementedException is thrown in the default case for the switch statements in the OnChangeScreen command - although you probably know that already.

The reason why is because none of the earlier case statements match true. They don't match true because perhaps you haven't added a CONST string for your new view to the IssueVision.Common.ViewTypes class or perhaps there is a typo between the CONST value and the CommandParameter value you have specified in your new menu item in MainPage.xaml. If you look at the OnChangeScreenCommand method you'll see there is a string (g) parameter in it's signature - that is the value passed via the CommandParameter defined in the menu item.

To create a new view, lets call it "About"

1. Add a menu item in one of the MainPage.xaml menus; in either the LoggedInMenuContent or the LoggedOutMenuContent. Give it whatever name you like, the command must be bound to the ChangeScreenCommand and the CommandParameter can be "About".
2. Add a CONST string to the IssueVision.Common.ViewTypes, where the constant value matches the CommandParameter defined in 1.
public const string AboutView = "About"
3. Add a case statement to the OnChangeScreenCommand method (don't forget there are 2 switch statements - as you pointed out in your post).
case ViewTypes.AboutView
// open the About screen
CurrentScreenText = ViewTypes.AboutView;
4. Create a ViewModel called AboutViewModel and ensure it inherets from ViewModelBase, has the Export(ViewModelTypes.AboutViewModel) and PartCreationPolicy(CreationPolicy.NonShared) MEF attributes, and has a ImportingConstructor attributed Constructor and ICleanup implementation (like the existing ViewModels). Don't worry about any properties, methods or commands just yet.
5. Add a CONST string to the IssueVision.Common.ViewModelTypes, where the value matches the name of the new ViewModel.
public const string AboutViewModel = "AboutViewModel";
6. Create the About screen view (AboutView.xaml) as a UserControl, don't bother with anything else for now.
7. In the codebehind for AboutView.xaml ensure it inherits from ICleanup, has a standard MEF SatisfyImports in the constructor and has a ViewModel (object) property with the Import(ViewModelTypes.AboutViewModel) attribute which sets the DataContext. Ensure it also implements the ICleanup interface and then leave any other methods for now.

You should now have a working View that can be called from the menu, if so, now you can start to play with changing the look and feel by adding content, properties, commands and methods to the View and ViewModel.

Hope that helps, let me know if I missed something out...
GeneralRe: How do you add new views (User Control) Pin
Member 767071323-Mar-11 21:07
memberMember 767071323-Mar-11 21:07 
GeneralRe: How do you add new views (User Control) Pin
Weidong Shen24-Mar-11 3:48
memberWeidong Shen24-Mar-11 3:48 
QuestionWhy to register to Messages at Code-behind and not at ViewModel Level? Pin
TheCubanP20-Dec-10 11:33
memberTheCubanP20-Dec-10 11:33 
AnswerRe: Why to register to Messages at Code-behind and not at ViewModel Level? Pin
Weidong Shen20-Dec-10 14:43
memberWeidong Shen20-Dec-10 14:43 
GeneralMy vote of 5 Pin
levteck15-Dec-10 8:01
memberlevteck15-Dec-10 8:01 
GeneralMy vote of 5 Pin
Nitu8417-Nov-10 6:30
memberNitu8417-Nov-10 6:30 
GeneralRe: My vote of 5 Pin
Weidong Shen23-Nov-10 4:20
memberWeidong Shen23-Nov-10 4:20 
GeneralMy vote of 5 Pin
Abhinav S23-Oct-10 18:09
memberAbhinav S23-Oct-10 18:09 
GeneralRe: My vote of 5 Pin
Weidong Shen29-Oct-10 14:39
memberWeidong Shen29-Oct-10 14:39 
GeneralBig Fan - Any Ideas on Using EventToCommand In DataGridTemplateColumn.TemplateCell Pin
Joseph DeMilo15-Oct-10 9:20
memberJoseph DeMilo15-Oct-10 9:20 
GeneralRe: Big Fan - Any Ideas on Using EventToCommand In DataGridTemplateColumn.TemplateCell Pin
Weidong Shen17-Oct-10 4:32
memberWeidong Shen17-Oct-10 4:32 
GeneralMy vote of 5 Pin
niflens21-Jul-10 4:42
memberniflens21-Jul-10 4:42 
GeneralRe: My vote of 5 Pin
Weidong Shen26-Jul-10 8:51
memberWeidong Shen26-Jul-10 8:51 
QuestionHow do you wire up the service with the ViewModel? Pin
chapamanuel26-Jun-10 9:24
memberchapamanuel26-Jun-10 9:24 
AnswerRe: How do you wire up the service with the ViewModel? Pin
Weidong Shen26-Jun-10 11:20
memberWeidong Shen26-Jun-10 11:20 
Questionawesome work | Password Problems [modified] Pin
omacall8-Jun-10 23:09
memberomacall8-Jun-10 23:09 
AnswerRe: awesome work | Password Problems Pin
Weidong Shen9-Jun-10 5:15
memberWeidong Shen9-Jun-10 5:15 
GeneralOutstanding work Pin
Marcelo Ricardo de Oliveira27-May-10 16:19
memberMarcelo Ricardo de Oliveira27-May-10 16:19 
GeneralRe: Outstanding work Pin
Weidong Shen28-May-10 3:00
memberWeidong Shen28-May-10 3:00 
GeneralNice Article Pin
linuxjr22-May-10 2:01
memberlinuxjr22-May-10 2:01 
GeneralRe: Nice Article Pin
Weidong Shen22-May-10 4:20
memberWeidong Shen22-May-10 4:20 
GeneralGood stuff Pin
Pete O'Hanlon21-May-10 11:51
mvpPete O'Hanlon21-May-10 11:51 
GeneralRe: Good stuff Pin
Weidong Shen21-May-10 13:56
memberWeidong Shen21-May-10 13:56 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.171017.2 | Last Updated 8 Jul 2011
Article Copyright 2010 by Weidong Shen
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid