在WPF中从一个xaml导航到另一个

E_l*_*ner 2 c# wpf xaml

尽管事实上我对WPF完全陌生,但我仍然需要编写代码,单击一个按钮后,应用程序应打开另一个xaml。在网上搜索后,我以以下方式进行操作:

1.我创建了两个xaml文件,分别是“ Window1.xaml”和“ Window2.xaml”。

2.在我的“ App.xaml”文件中,让:

<Application x:Class="DiagramDesigner.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"        
    StartupUri="Window1.xaml">
Run Code Online (Sandbox Code Playgroud)

3.然后在“ Window1.xaml”中创建一个按钮:

<Button Name="Button" Click="Button_Click_1" MouseEnter="Button_MouseEnter_1" IsDefault="True"
        HorizontalAlignment="Center" VerticalAlignment="Center">
    Start
</Button>
Run Code Online (Sandbox Code Playgroud)

4.在“ Windwo1.xaml.cs”文件中,创建了以下两个功能:

    private void Button_Click_1(object sender, RoutedEventArgs e)
    { 
    }

    private void Button_MouseEnter_1(object sender, MouseEventArgs e)
    {
    }
Run Code Online (Sandbox Code Playgroud)

5.然后在单击按钮后打开“ Window2.xaml”,我改为:

    private void Button_Click_1(object sender, RoutedEventArgs e)
    { 
        NavigationService service = NavigationService.GetNavigationService(this);
        service.Navigate(new Uri("Window2.xaml", UriKind.RelativeOrAbsolute));
    }
Run Code Online (Sandbox Code Playgroud)

但这给了我错误,说service是空,程序崩溃了。我没有想办法解决这个问题。有什么建议么?谢谢。

Nik*_*a B 6

尝试这个:

private void Button_Click_1(object sender, RoutedEventArgs e)
{ 
    var window = new Window2();
    window.ShowDialog();
}
Run Code Online (Sandbox Code Playgroud)

您还应该阅读有关NavigationService类及其方法的文档,以避免进一步混淆此类的用途。这是一个不错的起点:http : //msdn.microsoft.com/zh-cn/library/system.windows.navigation.navigationservice.getnavigationservice%28v=vs.110%29.aspx