Mvvm后退按钮:Page和ViewModel失去命令绑定

时间:2016-02-26 09:20:03

标签: c# mvvm mvvm-light

我已经使用MVVM Light实现了以下模式: Calling ViewModel methods in response to Page navigation events using MVVM Light in WinRT

我将其与How to handle the back button on WP 8.1 using MVVM light?

结合使用
private static INavigationService CreateNavigationService()
{
    var navigationService = new NavigationService();
    navigationService.Configure("Details", typeof(DetailsPage));
    navigationService.Configure("Chart", typeof(ChartPage));

    // Handle back button
    HardwareButtons.BackPressed += (sender, args) => {
        navigationService.GoBack();
        args.Handled = true;
    };

    return navigationService;
}

导航到详细信息页面和/或图表页面工作,后退按钮也可以工作。但在那之后,我无法再次导航到其中一个页面。

看起来MainPage及其ViewModel没有重新加载(缓存?)。所以他们失去了约束力。 RelayCommand未设置,因此导航不再可行。

任何人都可以帮我吗?

编辑:找到解决方案:)

最好的问候,Rick

1 个答案:

答案 0 :(得分:2)

更改了ViewModel中的代码:

public MainViewModel(INavigationService navigationService)
{
    _navigationService = navigationService;

    DetailsCommand = new RelayCommand(() =>
    {
        navigationService.NavigateTo("Details", "My data");
    });
}

要:

public MainViewModel(INavigationService navigationService)
{
    _navigationService = navigationService;

    DetailsCommand = new RelayCommand(() =>
    {
        _navigationService.NavigateTo("Details", "My data");
    });
}

导航现在来回运作。