繁体   English   中英

在WPF MVVM Light中多次绑定到RelayCommand

[英]Multiple binding to RelayCommand in WPF MVVM Light

我已经开始使用WPF MVVM Light,现在我正试图在页面之间导航。

在MainWindow我添加了一个“BackButton”

<Button Command='{Binding Main.GoBack, Mode=OneWay}' />

它绑定到MainViewModel方法“RelayCommand GoBack”。

private RelayCommand _goBack;
    public RelayCommand GoBack
    {
        get
        {
            return _goBack
                ?? (_goBack = new RelayCommand(
                () =>
                    _navigationService.GoBack();
                }));
        }
    }

为什么此按钮仅更改一次视图? 如果我想点击它,那么它不起作用(没有任何事情发生)。 如果我通过另一个按钮改变另一个页面的页面,它再次开始工作并且只打算一次。

FrameNavigationService的部分实现:

public FrameNavigationService()
    {
        _pagesByKey = new Dictionary<string, Uri>();
        _historic = new List<string>();
    }
    public void GoBack()
    {
        if (_historic.Count > 1)
        {
            _historic.RemoveAt(_historic.Count - 1);
            NavigateTo(_historic.Last(), null);
        }
    }
    public void NavigateTo(string pageKey)
    {
        NavigateTo(pageKey, null);
    }

    public virtual void NavigateTo(string pageKey, object parameter)
    {
        lock (_pagesByKey)
        {
            if (!_pagesByKey.ContainsKey(pageKey))
            {
                throw new ArgumentException(string.Format("No such page: {0} ", pageKey), "pageKey");
            }

            var frame = GetDescendantFromName(Application.Current.MainWindow, "MainFrame") as Frame;

            if (frame != null)
            {
                frame.Source = _pagesByKey[pageKey];
            }
            Parameter = parameter;
            _historic.Add(pageKey);
            CurrentPageKey = pageKey;
        }
    }

我该怎么做才能解决这个问题? 也许我应该完全不同?

你根本不应该做goback。

除非你真的想使用期刊,否则使用框架和页面是一个坏主意。 回到桌面应用程序的最后一个视图是一个罕见的要求。 什么与他们不是一个网络浏览器。

也许你有这个要求。

如果你有一个框架然后你有它的日志,你可以在框架的导航服务上调用goback。 https://docs.microsoft.com/en-us/dotnet/api/system.windows.navigation.navigationservice.goback?view=netframework-4.8

你在页面上设置了keepalive。 https://docs.microsoft.com/en-us/dotnet/api/system.windows.controls.page.keepalive?view=netframework-4.8

您编写了该代码,它似乎主要是复制导航服务功能。 从你向我们展示的东西。

原样。

使用类型而不是魔术字符串作为键。 在编译时检查一个类型,一个魔术字符串不是,你可以犯错误。

你有没有探讨过这个问题? 我想也许这是告诉别人他们做错了什么的时间之一并没有真正帮助告诉他们应该如何诊断。

调试是任何开发人员的关键技能。

你有代码在你面前运行。

把断点放进去,逐步检查发生了什么。

当你导航时,最终会出现在_historic中?

当你goback时,究竟发生了什么?

当您第二次点击goback时,它会向下移动什么路径以及导致该状态的状态。

确保在GalaSoft.MvvmLight.CommandWpf中使用RelayCommand,而不是在GalaSoft.MvvmLight.Command.RelayCommand中使用

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM