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!

8 thoughts on “Experiments using MEF, MVVM and Silverlight 4 Beta – Part 4: Part Creator”

  1. Much better Davide, as you are dynamically creating new VMs. Though I think having the VM be so loose (object) is hurting you.

    Here is why, ViewModelProvider could be generic insteasd it is specific. If you move to each ViewModel implementing an interface (for example IMainViewModel for the MainVM), you can change the provider to be a ViewModelProvider, and have the import
    be TViewModel.

    Then to use ViewModelProvider you just instantiate the one you want. i.e.

    var provider = new ViewModelProvider;
    var vm = ViewModelProvider.GetVMInstance();

    but in another instance I could use it to get an OrderVM.

    var provider = new ViewModelProvider;

    etc…

Leave a Reply

Your email address will not be published. Required fields are marked *