Reputation: 3733
I am trying to use MEF and MVVMLight in order to build my application.
I have managed to wire something together now that works and Imports successfully but in the process I seem to have totally missed off the ViewModelLocator and I am just wondering how you use MEF properly with a ViewModelLocator and perhaps if you actually need one at all or whether my design has gone wrong?
So in my App.xaml I disable the startupUri and in App.xaml.cs I do this:
[Import("MainWindow", typeof(Window))]
public new Window MainWindow
{
get { return base.MainWindow; }
set { base.MainWindow = value; }
}
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
// Load catalog in normal way
...
MainWindow.Show();
}
My MainWindow code is this:
[Export("MainWindow", typeof(Window))]
public partial class MainWindow : Window
{
[ImportingConstructor]
public MainWindow([Import("MainViewModel")] MainViewModel vm)
{
InitializeComponent();
DataContext = vm;
}
}
Finally my ViewModel is this:
[Export("MainViewModel", typeof(MainViewModel))]
public class MainViewModel : ViewModelBase, IPartImportsSatisfiedNotification
{
// I do some MEF imports here also
}
But what am I doing this the right way or is there a more sensible approach? Can I really just ignore the ViewModelLocator?
Upvotes: 2
Views: 1396
Reputation: 5183
I don't know if this is the 'right' way, but I also don't use the ViewModelLocator directly. I generally use Prism, and implement MEF using the bootstrapper approach, but I wire up my views to their viewmodels by doing this:
[Import]
public TransactionViewModel ViewModel
{
get { return (TransactionViewModel)DataContext; }
set { DataContext = value; }
}
This is the property that represents my ViewModel in the codebehind of my view. This way I'm not doing anything to the constructor of my Window. In your example, you no longer have a default constructor (at least that you show). While that's probably not a problem here, if you get in the habit of doing this and then need to let WPF instantiate a view for you (say in a datacontext) you will have problems.
But other than this, what you are doing looks pretty standard to me. You might want to check out Prism's implementation of MEF too. Prism also includes Unity, which accomplishes a different purpose, and has other goodies too that make creating the app frameworks a lot easier.
Upvotes: 3