我试图在代码中从一页导航到另一页:

if (Game.IsShopping)
    NavigationService.Navigate("ShopPage.xaml", Game.CurrentShop);


但是,我在NavigationService上得到了一个空引用异常,说我当前页面的属性为空。为什么是这样?如何在我的页面上获得导航服务?

最佳答案

找到一个解决方案elsewhere on StackOverflow:我为NavigationService创建了一个包装器:

public static class Navigator
{
    private static NavigationService NavigationService {get;} = (Application.Current.MainWindow as MainWindow).mainFrame.NavigationService;

    public static void Navigate(string path, object param = null)
    {
        NavigationService.Navigate(new Uri(path, UriKind.RelativeOrAbsolute), param);
    }

    public static void GoBack()
    {
        NavigationService.GoBack();
    }

    public static void GoForward()
    {
        NavigationService.GoForward();
    }
}

08-06 14:56