c# - 在 WPF 中使用 Caliburn Micro 导入构造函数 MEF
问题描述
快速提问,我有几个在 ShellViewModel 中分配的视图模型(导出已用于这 3 个虚拟机)
[ImportingConstructor]
public ShellViewModel(MainWindowViewModel viewModel,
SelectionViewModel sViewModel,
GStatsViewModel gsViewModel)
{
mainWindowViewModel = viewModel;
selectionViewModel = sViewModel;
gStatsViewModel = gsViewModel;
}
问题是,我想将“服务”注入 MainWindowViewModel。
这是服务
[PartCreationPolicy(CreationPolicy.Shared)]
[Export(typeof(IObjService))]
public class ObjService : IObjService
{
private ObservableCollection<ObjA> objSource = new ObservableCollection<ObjA>();
public ObservableCollection<ObjA> ObjSource
{
get { return objSource; }
set
{
objSource= value;
NotifyPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([System.Runtime.CompilerServices.CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
在我的 MainWindowViewModel
private ObjService objService;
// Can I use the importing constructor here?
public MainWindowViewModel(// something here?)
{
// Setup service
// or something here?
问题是,我该怎么做?MainWindowViewModel 怎么能有一个导入构造函数,但它现在的工作方式是如何在 ShellViewModel 中拥有它的?
还有,这样可以吗?我希望视图模型始终具有 ObjA 的可观察集合的相同引用,因为这将在全球范围内使用......所以这是前进的方式吗?
谢谢
我的应用正在使用 MVVM 架构
编辑
如果我这样做
private ObjService objService;
[ImportingConstructor]
public MainWindowViewModel(ObjService serviceToUse)
{
// Setup service
objService = serviceToUse;
我从 Caliburn Micro 那里得到一个例外说
throw new Exception(string.Format("Could not locate any instances of contract {0}.", contract));
对于 IShell
在引导程序中我做
var batch = new CompositionBatch();
batch.AddExportedValue<IWindowManager>(new WindowManager());
batch.AddExportedValue<IEventAggregator>(new EventAggregator());
batch.AddExportedValue<IObjService>(new ObjService());
batch.AddExportedValue(container);
container.Compose(batch);
如果我在 MainWindowViewModel 中将构造函数更改为此,它可以工作......我不确定为什么它适用于接口而不是具体类。我认为这是因为它无论如何都会被翻译成一个新的具体类,所以你应该给它接口,对吗?
工作私有 IObjService objService 的部分;
[ImportingConstructor]
public MainWindowViewModel(IObjService serviceToUse)
{
// Setup service
objService = serviceToUse;
解决方案
推荐阅读
- javascript - Firebase 未使用 Javascript 将正确的图像上传到存储
- python - Python Pyodbc 查询因 .join(['?', list]) 上的替换参数列表而失败
- python - 将 WRF UTC 时间转换为本地时间
- javascript - 来自带有超链接的 Google 表格的 HTML 表格
- regex - Bash如何在一个模式之后找到一个模式
- java - 杰克逊反序列化和序列化具有不同的字段名称
- c++ - 如何将 C++ 字符串发送到 node.js?
- database - 集合包含查询的数据结构
- java - 您可以在 Spring REST 中序列化对象的属性而不是整个对象吗?(对象是类的一个字段)
- javascript - document.querySelectorAll 和 for 循环的问题