在 WPF 中从一个 xaml 导航到另一个 [英] Navigating from one xaml to another in WPF

查看:32
本文介绍了在 WPF 中从一个 xaml 导航到另一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尽管我对 WPF 完全陌生,但我需要编写一个代码,在其中单击一个按钮后,应用程序应该打开另一个 xaml.在网上搜索后,我是这样做的:

Despite the fact that I am totally a fresh to WPF, I need to write a code, in which after I click a button, the application should open another xaml. After searching on the web, I did in in the following way:

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

1.I created two xaml files, namely 'Window1.xaml' and 'Window2.xaml'.

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

2.In my 'App.xaml' file, I let:

<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">

3.然后在我的Window1.xaml"中,我创建了一个按钮:

3.Then in my 'Window1.xaml', I created a button:

<Button Name="Button" Click="Button_Click_1" MouseEnter="Button_MouseEnter_1" IsDefault="True"
        HorizontalAlignment="Center" VerticalAlignment="Center">
    Start
</Button>

4.在我的Windwo1.xaml.cs"文件中,我创建了这两个函数:

4.In my "Windwo1.xaml.cs" file, I created these two functions:

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

    private void Button_MouseEnter_1(object sender, MouseEventArgs e)
    {
    }

5.然后为了在点击按钮后打开Window2.xaml",我改为:

5.Then for opening "Window2.xaml" after clicking the button, I changed to:

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

但这给了我错误,说 service 为空,程序崩溃了.我没有想出任何方法来解决这个问题.有什么建议?谢谢.

But this gives me error, saying the service is null, and the program crashed. I didn't figure out any way to solve this. Any suggestions? Thanks.

推荐答案

试试这个:

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

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

You should also read the documentation on NavigationService class and its methods to avoid further confusion on what this class does. Here is a good place to start: http://msdn.microsoft.com/en-us/library/system.windows.navigation.navigationservice.getnavigationservice%28v=vs.110%29.aspx

这篇关于在 WPF 中从一个 xaml 导航到另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆