Experiments using MEF, MVVM and Silverlight 4 Beta – Part 2: Custom attributes

Note – this is a multi part post:

In the last post, I’ve used the new MEF framework available in Silverlight 4 Beta to build a simple MVVM sample exporting, importing and then composing the ViewModel object with the xaml View.

As pointed by Glenn Block in his last blog post, it’s not a good practice to use magic strings in the Export/Import attributes, so I decided to investigate further and to use custom ones.

The new VM class is now modified as follow:

[ExportMainPageVMAttribute]
public class MainPageViewModel : ViewModelBase
    {
public MainPageViewModel()
        {

        }
/// <summary>
/// A sample property
/// </summary>
[Import("aViewModelPropertyTextProvider")] public string aViewModelProperty { get; set; }
/// <summary>
/// A sample command
/// </summary>
[Import(typeof(ICommand))]
public ICommand aSampleCommand {get; set;}
    }

 You can note the presence of a custom attribute named [ExportMainPageVMAttribute] defined in this way:

[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class ExportMainPageVMAttribute : ExportAttribute
    {
public ExportMainPageVMAttribute(): base(typeof(ViewModelBase))
        {

        }
    }

This new type permits to export and make available to the view the instance of the VM class via a new custom [ImportMainPageVMAttribute]:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class ImportMainPageVMAttribute : ImportAttribute
    {
public ImportMainPageVMAttribute() : base(typeof(ViewModelBase))
        {

        }
    }

The project now uses composition to initialize the aViewModelProperty  and aSampleCommand via a string provider

public class TextProvider
    {
[Export("aViewModelPropertyTextProvider")]
public string ViewModelPropertyProvider { get { return "This is the content of a ViewModel property"; } }
    }

and an [Export] attribute for our sample command:

/// <summary>
/// A simple Command in SIlverlight 4 Beta
/// </summary>
[Export(typeof(ICommand))]
public class AViewCommand : ICommand
    {
public bool CanExecute(object parameter)
        {
            return true;
        }

public event EventHandler CanExecuteChanged;

        public void Execute(object parameter)
        {
            if (parameter != null)
if (parameter is string) MessageBox.Show((string)parameter);
        }
    }

As usually the source code is available for download here.

Happy Silverlighting!