我正尝试用MEF创建一个简单的模块化MVVM应用程序。我有一个ViewModel类和一个UserControl作为视图。我连接两个通过一个DataTemplate,像这样:ViewModel与MEF安装了两次
<DataTemplate DataType="{x:Type local:MyViewModel}">
<local:MyView />
</DataTemplate>
在视图中,我定义的视图模型作为静态资源,作出具有约束力的简单:
<UserControl.Resources>
<local:MyViewModel x:Key="ViewModel" />
</UserControl.Resources>
然后我绑定是这样的:
<Grid DataContext="{StaticResource ResourceKey=ViewModel}">
<TextBlock Text="{Binding Text}" />
</Grid>
这一切都按预期工作,没有MEF。然而,正如我瞄准模块化,我使用MEF来发现我的ViewModel类。我有一个属性导出我的ViewModel类:
[Export(typeof(MyViewModel))]
public class MyViewModel
{
// ...
}
,我使用MEF视图模型动态加载到我的壳在App.xaml.cs:
private void Application_Startup(object sender, StartupEventArgs e)
{
var shell = new MainWindow();
var catalog = new AssemblyCatalog(this.GetType().Assembly);
var container = new CompositionContainer(catalog);
shell.Contents.ViewModel = container.GetExportedValues<MyViewModel>().First();
shell.Show();
}
现在,在这一点上,MEF当它加载虚拟机时创建我的ViewModel的一个实例,而我的View在它将虚拟机声明为资源时创建另一个实例。 (这很容易通过在构造函数中设置断点来检查。)
问题是,我应该如何将由MEF创建的实例传递给我的资源声明?我可以将特定实例声明为资源吗?全码
的DropBox链接: https://www.dropbox.com/sh/pbdl029d26sx7gl/AAA6po50dLjbJSoNPBhCyWZ3a?dl=0
修改我的基础结构使用DataContextSpy基于这个答案: http://stackoverflow.com/a/5402653/5219911 让问题开放一下,万一有人提出另一个灵魂,但这似乎现在工作。 –