WPF 页面导航 C# 不起作用

本文关键字:不起作用 导航 WPF | 更新日期: 2023-09-27 17:57:24

我对C#和WPF架构很陌生。我正在尝试创建一个具有简单页面导航的应用程序。我已将主窗口从窗口更改为导航窗口。我还在 MainWindow.xaml 中放置了以下代码.cs

 public void View(string newView) 
    {
        Uri view = new Uri(newView, UriKind.Relative);
        NavigationService nav = NavigationService.GetNavigationService(this);
        if (nav != null) 
        {   
            nav.Navigate(view);
        }
        else
        {
            MessageBox.Show("NavNull");
        }
    }

我从默认源("HubView.xaml")调用此方法,它位于名为"页面"的文件夹中。代码如下所示

 public void Button_Click(object sender, RoutedEventArgs e)
    {
        View = @"'Pages'UserAdd.xaml";
        MainWindow mainWindow = new MainWindow();
        mainWindow.View(View);
     }

但是,当我单击该按钮时,将显示消息框,指示nav等于null。我已经通读了这个问题和随后的答案,但我仍然不完全理解。

任何建议将不胜感激!


编辑:

这是"MainWindow.xaml":

<NavigationWindow x:Class="Container.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    ResizeMode="CanMinimize"
    Title="MainWindow" Height="350" Width="525" Source="Pages/HubView.xaml" WindowStyle="ThreeDBorderWindow" ShowsNavigationUI="False">
    </NavigationWindow>

如您所见,窗口是一个导航窗口。

WPF 页面导航 C# 不起作用

> NavigationService用于 WPF 中的页面导航,就像在浏览器中一样,要使其正常工作,您需要向 MainWindow.xaml 添加Frame

<Grid>
    <Frame x:Name="mainFrame"/>
    <Button x:Name="btnPage1" Content="Page 1" Width="200" Height="50"
            Click="btnPage1_Click"/>        
</Grid>

并使用NavigationService进行导航,例如

private void btnPage1_Click(object sender, RoutedEventArgs e)
{
    mainFrame.NavigationService.Navigate(new Uri("Page1.xaml", UriKind.Relative));
}

编辑创建 1 个窗口和 2 个页面

MainWindow.xaml

<NavigationWindow 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" Source="Page1.xaml">

第 1.xaml 页

<Page x:Class="WpfApplication1.Page1"
  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="Page1">
<Grid>
    <TextBlock Text="Page 1" FontWeight="Bold" />
    <Button Margin="0,40" Content="Goto Page 2" Width="200" Height="50"
            Click="Button_Click"/>
</Grid>

第 1.xaml 页.cs

public partial class Page1 : Page
{
    public Page1()
    {
        InitializeComponent();
    }
    private void Button_Click(object sender, RoutedEventArgs e)
    {
        this.NavigationService.Navigate(new Uri("Page2.xaml", UriKind.Relative));
    }
}

NavigationWindow具有 NavigationService 的属性,因此无需创建新变量。希望有帮助。注意Page2.xaml只是一个空白页