【发布时间】:2015-09-28 15:28:31
【问题描述】:
我正在尝试使用 MEF 创建一个简单的模块化 MVVM 应用程序。我有一个 ViewModel 类和一个 UserControl 作为视图。我通过 DataTemplate 将两者连接起来,如下所示:
<DataTemplate DataType="{x:Type local:MyViewModel}">
<local:MyView />
</DataTemplate>
在 View 中,我将 ViewModel 定义为 StaticResource,以简化绑定:
<UserControl.Resources>
<local:MyViewModel x:Key="ViewModel" />
</UserControl.Resources>
然后我这样绑定:
<Grid DataContext="{StaticResource ResourceKey=ViewModel}">
<TextBlock Text="{Binding Text}" />
</Grid>
这一切都可以在没有 MEF 的情况下按预期工作。但是,由于我的目标是模块化,因此我使用 MEF 来发现我的 ViewModel 类。我的 ViewModel 类上有一个 Export 属性:
[Export(typeof(MyViewModel))]
public class MyViewModel
{
// ...
}
我使用 MEF 将 ViewModel 动态加载到 App.xaml.cs 中的 shell:
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 在加载 vm 时创建了我的 ViewModel 的一个实例,而我的 View 在将 vm 声明为资源时创建了另一个实例。 (这很容易通过在构造函数中设置断点来检查。)
问题是,我应该如何将 MEF 创建的实例传递给我的资源声明?我可以将该特定实例声明为资源吗?
带有完整代码的 DropBox 链接: https://www.dropbox.com/sh/pbdl029d26sx7gl/AAA6po50dLjbJSoNPBhCyWZ3a?dl=0
【问题讨论】:
-
根据这个答案使用 DataContextSpy 修改了我的基础架构:stackoverflow.com/a/5402653/5219911 让这个问题稍微开放一下,以防有人提出另一个想法,但这似乎目前可行。