【问题标题】:issues navigating to another page导航到另一个页面的问题
【发布时间】:2014-12-17 20:28:17
【问题描述】:

这是我的主窗口

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="5*" />
            <RowDefinition  />
        </Grid.RowDefinitions>

        <Label Grid.Row="0">This is Page 1</Label>
        <Button Grid.Row="1" Content="Next" Click="Next_Click" />

    </Grid>
</Window>

我还有另一个页面叫做 Page2

<Page x:Class="WpfApplication1.Page2"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      mc:Ignorable="d" 
      d:DesignHeight="300" d:DesignWidth="300"
    Title="Page2">

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="5*" />
            <RowDefinition  />
        </Grid.RowDefinitions>

        <Label Grid.Row="0">This is Page 2</Label>

    </Grid>
</Page>

在 MainWindow 的下一个按钮上,我想导航到 Page2。为此,我为该按钮设置了以下事件处理程序。

    private void Next_Click(object sender, RoutedEventArgs e)
    {
        NavigationService nav = NavigationService.GetNavigationService(this);
        nav.Navigate(new Uri("Page2.xaml", UriKind.RelativeOrAbsolute));
    }

但是对 NavigationService.GetNavigationService(this) 的调用返回 null。我做错了什么?

【问题讨论】:

  • 请详细说明抛出了哪些异常。
  • 页面旨在用于导航应用程序(通常带有后退和前进按钮,例如 Internet Explorer)。为什么不使用 NavigationWindow 或 Frame 来托管您的页面?
  • @Tilman:添加了有问题的粗体错误。

标签: c# wpf xaml navigation


【解决方案1】:

问题是您从窗口请求导航服务。 WPF 有两个导航器:NavigationWindowFrame。这种窗口和控件具有处理内容导航的 NavigationService。 例如,在窗口中,您可以使用如下所示的框架:

<Window 
x:Class="NavigationSample.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300"
>
<StackPanel>
    <Frame x:Name="_mainFrame" />
</StackPanel>

然后,在您的代码开始时,您可以执行以下操作:

_mainFrame.Navigate(new Page1());

另一种变体是直接使用 NavigationService 属性:

_mainFrame.NavigationService.Navigate(new Page1());

查看此链接以了解 GetNavegationService 方法的工作原理:NavigationService.GetNavigationService Method

您可以在这里找到更多信息:Navigation

【讨论】:

  • 答案抄自technet.microsoft.com/en-ca/…,不加引号,参考。我认为这是抄袭。
  • 你好@PaulSnow,我前段时间编辑了我的答案,试图更好地解释约翰史密斯如何解决他的问题。你能撤消你的反对票吗?
猜你喜欢
  • 2021-09-08
  • 2021-09-11
  • 1970-01-01
  • 2022-06-18
  • 2015-08-12
  • 1970-01-01
  • 2012-11-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多