Caliburn.micro parent->child 和 child->parent 互动

Caliburn.micro parent->child and child->parent interactions

我正在使用 Caliburn.micro 开发 WPF 应用程序。在那里我有一个扩展 Conductor 的 mainViewModel 和两个扩展 Screen 的 subviewModel。这两个视图模型由我的 MainViewModel 中的选项卡控件激活。我有属于 MainViewModel 的字符串,我需要将这些字符串传递给两个 subViewModel。我需要传递给 subViewModels 的字符串在 MainView 中绑定到文本框。我想将这些字符串传递给 subViewModel,即使这些字符串是从 MainViewModel 更改的,我也需要更新我的 subViewModels。现在我在每个 subViewModel 的构造函数中将 MainViewModel 作为参数,但我很确定有更好的方法 基本上我想将 child 属性 绑定到 parent 属性 并报告其中任何一个 属性 已在 parent 或在 child 视图模型中。 你能给我指明好的方向吗?

您可以使用 EventAggregators 来实现这一点。

For those unfamiliar, an Event Aggregator is a service that provides the ability to publish an object from one entity to another in a loosely based fashion.

您可以阅读有关事件聚合器的更多信息here

您首先定义包含要传递的消息的 CustomMessage。

public class CustomMessage
{
    public string String1 { get; set; }
}

现在您继续 ParentViewModel 并创建一个事件聚合器实例。

private IEventAggregator _eventAggregator;
[ImportingConstructor]
public ShellViewModel(IEventAggregator eventAggregator)
{
_eventAggregator = eventAggregator;
_eventAggregator.Subscribe(this);
}

在绑定到文本框的 属性 的 Setter 中,您现在可以添加代码以使用事件聚合器发布消息。

例如,

public string String1
{
    get => _string1;
    set
    {
        if (_string1.Equals(value)) return;

        _string1 = value;
        _eventAggregator.PublishOnUIThread(new CustomMessage
        {
            String1 = _string1,
        });

    }

}

现在您前往 Child 查看模型并订阅事件聚合器。

private IEventAggregator _eventAggregator;
[ImportingConstructor]
public SecondWinViewModel(IEventAggregator eventAggregator)
{
    _eventAggregator = eventAggregator;
    _eventAggregator.Subscribe(this);
}

为了订阅特定消息(在本例中为 CustomMessage),您需要实现接口 IHandle。

[Export(typeof(SecondWinViewModel))]
public class SecondWinViewModel : Screen, IHandle<CustomMessage>

该界面需要一个方法,您可以使用该方法接收消息并更新 Child Window.

中所需的 属性
public void Handle(CustomMessage message)
{
    String1 = message.String1;
    NotifyOfPropertyChange(nameof(String1));
}

您可以通过在 CustomMessage 中添加更多属性来对多个参数执行相同的操作。同理,可以从ChildVm向ParentVm传递消息。