首页 > 解决方案 > 在 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;

标签: c#wpfmvvmmefcaliburn.micro

解决方案


推荐阅读