在 WPF MVVM Light 中多重绑定到 RelayCommand

Multiple binding to RelayCommand in WPF MVVM Light

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

在主窗口中我添加了一个 "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

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

您编写了该代码,它似乎在很大程度上重现了导航服务功能。根据您向我们展示的内容。

原样。

使用类型而不是魔术字符串作为键。在编译时会检查类型,但不会检查魔术字符串,您可能会出错。

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

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

您面前有代码运行。

设置断点,单步执行并检查发生了什么。

导航时,_historic 中的结果是什么?

当你回去的时候,到底发生了什么?

当您第二次单击回退时,它会沿着什么路径向下走,是什么状态导致的。

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