WPF页面的NavigationService为null,如何在页面上获取NavigationService?

ilmyapht  于 2023-01-18  发布在  其他
关注(0)|答案(3)|浏览(222)

我正在尝试在代码中从一个页面导航到另一个页面:

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

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

9cbw7uwe

9cbw7uwe1#

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

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();
    }
}
8fsztsew

8fsztsew2#

首先设置一个帧(在xamel主窗口中渲染)

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

然后使用navigate,因此出现空引用异常

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));
}
mec1mxoz

mec1mxoz3#

如果框架元素在主窗口中,则将其添加到MainWindow.xaml.cs:

public static NavigationService NavigationService => ((MainWindow)Application.Current.MainWindow).frmMain.NavigationService;

注意:frmMain是XAML文件中框架的名称

<Frame x:Name="frmMain" />

使用方法:

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

相关问题