【问题标题】:Caliburn.Micro Calling a viewmodel from UserControlCaliburn.Micro 从 UserControl 调用视图模型
【发布时间】:2016-07-02 11:56:50
【问题描述】:

我有一个 AppViewModel,它在窗口顶部包含一个菜单。在 AppViewModel 构造中,我展示了一个 UserControl。在这个 UserControl 中,我有一个按钮,它调用另一个视图模型 (UserControl)。

这个想法是保留菜单并处理窗口的内容。所以,我有 1 个窗口和 2 个用户控件。这是对的吗?

如何从 UserControl 内的按钮调用另一个 ViewModel?或者,我必须从窗口调用它?但是按钮在 UserControl 里面!

我的代码:

class AppViewModel : Conductor<object>
{
    private bool _MenuIsVisible;

    public bool MenuIsVisible
    {
        get { return _MenuIsVisible; }
        set
        {
            if (_MenuIsVisible != value)
            {
                _MenuIsVisible = value;
                NotifyOfPropertyChange(() => MenuIsVisible);
            }
        }
    }

    public AppViewModel()
    {
        MenuIsVisible = true;
        _ShowTutorial();
    }

    private void _ShowTutorial()
    {
        ActivateItem(new FirstViewModel());
    }

}



public class FirstViewModel : Screen
{
    protected override void OnActivate()
    {
        base.OnActivate();
    }
}

在 FirstViewModel 上,我有一个需要调用 SecondViewModel 的按钮。

【问题讨论】:

    标签: c# wpf mvvm user-controls caliburn.micro


    【解决方案1】:

    要从第一个 ViewModel 导航到第二个 ViewModel,您可以在第一个 ViewModel 中使用如下方法:

    public void NavigateToSecond()
    {
        var conductor = this.Parent as IConductor;
        conductor.ActivateItem(new SecondViewModel());
    }
    

    父母指的是负责为您导航的售票员。

    【讨论】:

    • 完美运行!非常感谢!
    • 在 SecondViewModel 我有一个“后退按钮”,这样做是否正确?谢谢!
    • 也可以使用 Screen 的 TryClose 方法。如果您还没有这样做,我强烈推荐这里的优秀文档:caliburnmicro.com/documentation/composition
    • TryClose 工作,但它没有再次显示前一个屏幕:( 你知道为什么吗?
    • 因为您使用的是 Conductor,它只在内存中保留 1 个 ViewModel。如果你想让多个 ViewModel 保持活跃,你需要使用类似的东西: Conductor.Collection.OneActive.
    猜你喜欢
    • 2013-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-02
    • 2014-11-28
    • 2015-05-02
    • 2013-05-14
    相关资源
    最近更新 更多