我是C#和WPF架构的新手。我正在尝试使用简单的页面导航创建一个应用程序。我已将我的MainWindow从Window更改为NavigationWindow。我还将以下代码放在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”)调用此方法,这是在名为“Pages”的文件夹中。代码看起来像这样
public void Button_Click(object sender, RoutedEventArgs e)
{
View = @"\Pages\UserAdd.xaml";
MainWindow mainWindow = new MainWindow();
mainWindow.View(View);
}
然而,当我单击按钮时,会显示消息框,指示nav等于null。我已经阅读了this问题和随后的答案,但我仍然不完全理解。
任何建议都将不胜感激!
编辑:
这是“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>
如您所见,窗口是导航窗口。
答案 0 :(得分:0)
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">
的Page1.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>
Page1.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只是一个空白页