我正在寻求一些帮助,我希望那里的一些好人能给我一个提示:)
我正在使用 MVVM Light 构建一个新应用程序。在此应用程序中,当创建视图时,它会使用 MEF 导入实例化相应的 ViewModel。
这是一些代码:
public partial class ContractEditorView : Window
{
public ContractEditorView ()
{
InitializeComponent();
CompositionInitializer.SatisfyImports(this);
}
[Import(ViewModelTypes.ContractEditorViewModel)]
public object ViewModel
{
set
{
DataContext = value;
}
}
}
这是 ViewModel 的导出:
[PartCreationPolicy(CreationPolicy.NonShared)]
[Export(ViewModelTypes.ContractEditorViewModel)]
public class ContractEditorViewModel: ViewModelBase
{
public ContractEditorViewModel()
{
_contract = new Models.Contract();
}
}
现在,如果我想打开一个新窗口以创建新合同,这很有效……或者换句话说,如果我不需要传递现有合同的 ID,那就完美了。
但是,假设我想使用相同的视图来编辑现有合同。在这种情况下,我将向同一个视图添加一个新的构造函数,它接受模型 ID 或模型对象。
“不幸的是” ViewModel 总是以相同的方式创建:
[Import(ViewModelTypes.ContractEditorViewModel)]
public object ViewModel
{
set
{
DataContext = value;
}
}
据我所知,这会在合成时调用相应 ViewModel 的标准/无参数构造函数。
那么我想知道的是如何区分这种行为?如何在合成期间调用特定的构造函数?或者如何在导入期间传递一些参数?
如果这个问题听起来很愚蠢,我真的很抱歉,但我最近才开始使用 MEF!
提前致谢,
干杯,吉安卢卡。