事件聚合器和 WIndowManager 的设计时支持

Design Time Support with Event Aggregator AND WIndowManager

我必须使用 Caliburn.Micro 2.0.2 创建一个 WPF 应用程序用于我的学士考试。

在此应用程序中,三个不同的视图将显示在一个 Shell (Window) 中,并且它们必须相互通信。所以我需要事件聚合器。 我还需要 Window 管理器来显示其他对话框。

我的实际问题是我必须将所有这些与完整的设计时支持结合在一起。 不幸的是,没有这种情况的例子。

Caliburn.Micro 的文档说视图模型中需要一个默认构造函数,以提供设计时支持。但是,事件聚合器和 Window 管理器在视图模型中用作构造函数参数,因此一开始没有默认构造函数。

文档还说,在这种情况下,应使用 ViewModelLocator 来获得设计时支持。 不幸的是,有关 ViewModelLocator 的部分没有提供有关如何执行此操作的足够信息。

另一个想法可能是像这样链接构造函数:

public class ExampleViewModel : PropertyChangedBase
{
    private readonly IEventAggregator eventAggregator;
    private readonly IWindowManager windowManager;

    public ExampleViewModel() : this(null)
    {
    }

    public ExampleViewModel(IEventAggregator eventAggregator) : this(eventAggregator, null)
    {
    }

    public ExampleViewModel(IEventAggregator eventAggregator, IWindowManager windowManager)
    {
        this.eventAggregator = eventAggregator;
        this.windowManager = windowManager;

        // doing everything needed for the Design Time Support
    }
}

但我不知道这是否最终会奏效。

希望有人能帮我解决这个问题。

您可以在设计时使用单独的 DataContext (ViewModel)。您需要在使用视图模型的地方添加 XAML:

<UserControl 
    ...
    xmlns:dt="clr-namespace:YourProject.DesignTimeHelpers;assembly=YouAssembly"
    d:DataContext="{Binding Source={x:Static dt:DesignTimeModels.ExampleViewModelForDesignTime}}">

有视图模型的静态 DesignTimeModels class:

public static class DesignTimeModels
{
    public static ExampleViewModel ExampleViewModelForDesignTime { get; set; }

    // static constructor
    static DesignTimeModels()
    {
        ExampleViewModelForDesignTime = 
            new ExampleViewModel(new EventAggregator(), new WindowManager());
    }
}

主要思想是通过带有所需参数的静态初始化器创建视图模型的实例。

如果您想使用 IoC container(例如 Caliburn)来实例化 EventAggregatorWindowManager,您可以使用 ServiceLocator 模式。例如:

// static constructor
static DesignTimeModels()
{
    var eventAggregator = ServiceLocator.Get<IEventAggregator>();
    var windowManager = ServiceLocator.Get<IWindowManager>();

    ExampleViewModelForDesignTime = 
        new ExampleViewModel(eventAggregator , windowManager);
}