2015-06-22 103 views
0

我对C#和WPF体系结构非常陌生。我正在尝试使用简单的页面导航创建应用程序。我已将我的MainWindow从Window更改为NavigationWindow。我也把下面的代码在MainWindow.xaml.csWPF页面导航C#不工作

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等于空。我已经通过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

NavigationService是在WPF页面导航就像一个浏览器,并为工作,你需要一个Frame添加到您的MainWindow.xaml

<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具有的性质所以不需要创建新的变量。希望有所帮助。 注意 Page2.xaml只是一个空白页面

+0

MainWindow.xaml已经是一个NavigationWindow。 – fergul