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!




December 5th, 2009 at 17:47
[...] This post was mentioned on Twitter by Davide Zordan and Corrado Cavalli, Larry King. Larry King said: Experiments using MEF, MVVM and Silverlight 4 Beta – Part 2 … http://bit.ly/4x9ZAS #SL #RIA [...]
December 6th, 2009 at 12:58
[...] the last post I’ve inserted custom attributes in my MVVM implementation using MEF, in the meantime some [...]
December 7th, 2009 at 01:58
[...] This post was Twitted by JustinAngel [...]
December 13th, 2009 at 22:30
[...] Part 2: Custom attributes [...]