WPF页面的NavigationService为null。如何在页面上获得NavigationService?

时间:2018-09-21 20:38:59

标签: c# wpf

我正在尝试将代码从一页导航到另一页:

@Query("SELECT t FROM Table t WHERE t.status.id = ?1"
            + " AND t.startDate >= ?2 AND t.startDate <= ?3"
            + " AND t.startDate::time >= ?4 AND t.startDate::time <= ?5")
Page<Item> findByStatusIdAndDateRange(Long activeId, final long startDate, final long endDate, final String startTime, final String endTime, Pageable pageRequest);

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

2 个答案:

答案 0 :(得分:2)

找到了解决方案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();
    }
}

答案 1 :(得分:0)

首先设置一个框架(在xamel主窗口中进行渲染)

<DockPanel>
    <Frame x:Name="mainFrm" />
</DockPanel>

然后使用Navigation,因此使用null引用异常

mainFrm.NavigationService.Navigate(new Uri("ShopPage.xaml", Game.CurrentShop));  

或如果您在控制器操作代码块中,请在下面使用

void ExampleControllButton_Click(object sender, RoutedEventArgs e)
{
this.NavigationService.Navigate(new Uri("ShopPage.xaml", Game.CurrentShop));
}