Sunday, April 24, 2011 10:35:00 PM

So I'm using MVVM pattern with Prism and MEF in the sample application that I'm currently working on. My practice when not using PRISM and MEF was to wire up the ViewModel to the View by putting markup in the View's xaml to specify the ViewModel class. An example would be

<UserControl.DataContext>

<vm:CustomerHomeViewModel/>

</UserControl.DataContext/>

Now let's say that in the ViewModel class we need to use something that is imported from MEF. This could be the IRegionManager, or one of my own classes that I'm importing. In this example I'm importing a SampleData class, and using the SampleData.Name value as DisplayName property that I've wired up on my View. I set a breakpoint in 'get' statement and I see that when this line is hit, that SampleData is null. The Import is not working. Why? Because MEF didn't create this ViewModel. I created it in xaml rather than letting MEF create it.

 

[Import]

        CustomerSampleData SampleData;

      

        public string DisplayName

        {

            get{

stringit = SampleData.Name;

                     return it;

            }

            set {

                q    _displayName = value;

            }

        }

To fix this I need to let MEF create the ViewModel. I can do this 2 ways that I know of. First, I could put a ViewModel property into the codebehind of the View file as follows (and remove the xaml that creates the ViewModel):

[Import]

Customers.ViewModels.CustomerHomeViewModelViewModel

{

set{ this.DataContext = value; }

}

Or I found that Jeremy Likness has create is using Markup Extensions in a sample show here: http://www.wintellect.com/CS/blogs/jlikness/archive/2011/04/14/creating-a-markup-extension-for-mef-with-silverlight-5.aspx so that you can still create the ViewModel in xaml. I haven't tried this yes, but its worth a look especially if you prefer not to have code behind in your Views.

Comments are closed on this post.