【问题标题】:Navigating from one xaml to another in WPF在 WPF 中从一个 xaml 导航到另一个 xaml
【发布时间】:2014-06-18 12:05:18
【问题描述】:

尽管我对 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">

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

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

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

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

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

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));
    }

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

【问题讨论】:

    标签: c# wpf xaml


    【解决方案1】:

    试试这个:

    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

    【讨论】:

    • 感谢您的回答。它给出了一个错误,说:非静态字段、方法或属性“System.Windows.Window.ShowDialog()”需要对象引用。
    【解决方案2】:

    NavigationService 无法在使用 Windowhttp://msdn.microsoft.com/en-us/library/ms750478(v=vs.110).aspx 的经典 WPF 桌面应用程序中使用。

    您可以在 Page 类实例之间导航,但不能在 Window 类实例之间导航。

    您必须使用WPF. How hide/show main window from another window中所示的技术手动显示和隐藏它

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多