【问题标题】:Setting Caliburn.Micro ControlContent from another ViewModel从另一个 ViewModel 设置 Caliburn.Micro ControlContent
【发布时间】:2013-10-22 03:11:20
【问题描述】:

我是 Caliburn.Micro 的新手(以及 MVVM),我正在尝试通过子视图模型中的按钮激活位于 ShellViewModel 的导体的屏幕(由售票员呼叫)。我见过的所有教程都有在实际外壳中切换的按钮,所以我有点迷茫。

所有 ViewModel 共享命名空间 SafetyTraining.ViewModels

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

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

    public void ShowMainView()
    {
        ActivateItem(new MainViewModel());
    }
}

ShellViewXAML

<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
    }
}

MainViewXAML

<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());

【问题讨论】:

    标签: c# wpf caliburn.micro


    【解决方案1】:

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

    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);
    }
    

    【讨论】:

    • 是自定义差异还是版本差异(我使用的是 1.5.2),您是通过 Conductor no param(对我无效)和 Active 而不是 ActivateItem 来完成的?只是想知道
    • @PRX 对不起,我不完全明白你在问什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-06
    • 2022-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多