设置 Caliburn.Micro Control来自另一个视图模型的内容

本文关键字:模型 视图 另一个 Caliburn Micro Control 设置 | 更新日期: 2023-09-27 18:35:28

我是Caliburn.Micro(和MVVM)的新手,我正在尝试从子视图模型中的按钮(由指挥家调用)激活位于ShellViewModel的导体的屏幕。我看过的所有教程在实际的 shell 中都有按钮,可以在它们之间切换,所以我有点迷茫。

所有视图模型共享命名空间SafetyTraining.ViewModels

ShellViewModel(第一次使用shell,所以我可能以错误的方式使用它)

public class ShellViewModel : Conductor<object>.Collection.OneActive, IHaveDisplayName
{        
    public ShellViewModel()
    {
        ShowMainView();
    }
    public void ShowMainView()
    {
        ActivateItem(new MainViewModel());
    }
}

ShellView XAML

<UserControl x:Class="SafetyTraining.Views.ShellView"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<DockPanel>
    <ContentControl x:Name="ActiveItem" />
</DockPanel>

MainViewModel - 主屏幕(正确显示)。

public class MainViewModel : Screen
{
    public void ShowLoginPrompt()
    {
        LoginPromptViewModel lg = new LoginPromptViewModel();//This does happen
    }
}

MainView XAML

<Button cal:Message.Attach="[Event Click] = [ShowLoginPrompt]">Login</Button> 

LoginPromptViewModel

public class LoginPromptViewModel : Screen
{
    protected override void OnActivate()
    {
        base.OnActivate();
        MessageBox.Show("Hi");//This is for testing - currently doesn't display
    }
}

编辑工作代码:

稍微修改了Sniffer的代码以正确适应我的结构。谢谢:)

var parentConductor = (Conductor<object>.Collection.OneActive)(this.Parent);
        parentConductor.ActivateItem(new LoginPromptViewModel());

设置 Caliburn.Micro Control来自另一个视图模型的内容

你做的一切都是正确的,但你错过了一件事:

public void ShowLoginPrompt()
{
    LoginPromptViewModel lg = new LoginPromptViewModel();//This does happen
}

您正在创建 LoginPromptViewModel 的实例,但您没有告诉导体激活此实例,因此永远不会调用OnActivate()方法。

现在,在我给你一个解决方案之前,我应该提出几点建议:

  1. 如果您使用MainViewModel在不同的视图模型之间导航,那么将MainViewModel本身设为导体是合适的。

  2. 如果您不是那样使用它,那么也许您应该将导航到LoginPromptViewModel的按钮放在ShellView本身中。

现在回到你的问题,因为你的MainViewModel Screen扩展,那么它有一个Parent属性,它指的是导体,所以你可以这样做:

public void ShowLoginPrompt()
{
    LoginPromptViewModel lg = new LoginPromptViewModel();//This does happen
    var parentConductor = (Conductor)(lg.Parent);
    parentConductor.Activate(lg);
}