How to use MVVM and MEF with DataTemplate?
I am trying to use MEF on a new project within my application. Things work at the main app level, but in this separate project whose assembly is included in the main app (its a UserControl) I am wondering about something... If I have a UserControl, and in it I have the following:
<UserControl.Resources>
<DataTemplate DataType="{x:Type vm:MyViewModel}" >
<local:MyView />
</DataTemplate>
</UserControl.Resources>
<vm:MyViewModel />
In my MyViewModel, I Export some stuff, and the assemblies seem to be composed just fine (Im using the CompositionInfoTextFormatter to check this). But my VM is not instantiated by MEF开发者_开发技巧, or at least the constructor never gets called. And when it does get called it appears to be from the WPF framework, not MEF.
What is the right way to A) In xaml, associate my VM with its view with MEF (if different from above) and B) How do I instantiate my VM so that MEF controls it, and therefore the Exports and Imports work?
Currently they dont, which is why Im trying to make sense of this all :)
Given what you're showing above, MEF doesn't come into play at all here. You have a completely self contained UserControl.
In fact, the UserControl you're showing could be done much simpler:
That's pretty much the same thing as what you wrote above. There really is no reason for this UserControl to exist, since you could just put in MyView
directly.
That being said, I personally use MEF for DataTemplate generation. The way I handle it is that I have a class that exports a ResourceDictionary
, and have the main application import the ResourceDictionary
and merge it with the main Application Resources.
I use this export class to export a DataTemplate that maps from each View to the corresponding ViewModel. This works very well, since it allows a complete VM-first approach with no knowledge of the View from any VM.
Edit:
It sounds like your problem is that [Import]
s are not being filled, since you're using WPF for construction instead of MEF. If this is the case, you'll want to use the PartInitializer class available here. For details, see Glenn Block's blog.
You might have a look at the sample applications of the WPF Application Framework (WAF). They show how MEF is used to instantiate the ViewModel classes.
精彩评论