在WPF中从一个示例导航到另一个示例
本文关键字:一个 导航 另一个 WPF | 更新日期: 2023-09-27 18:09:23
尽管我完全不熟悉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。然后在我的窗口。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"。点击按钮后,我改成:
private void Button_Click_1(object sender, RoutedEventArgs e)
{
NavigationService service = NavigationService.GetNavigationService(this);
service.Navigate(new Uri("Window2.xaml", UriKind.RelativeOrAbsolute));
}
但是这给了我错误,说service
是空的,程序崩溃了。我没想出解决这个问题的办法。有什么建议吗?谢谢。
试试这个:
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
NavigationService不能在使用Window
类的经典WPF桌面应用程序中使用http://msdn.microsoft.com/en-us/library/ms750478(v=vs.110).aspx.
您可以在Page
类实例之间导航,但不能在Window
类实例之间导航。
必须使用WPF中所示的技术手动显示和隐藏它。如何从另一个窗口隐藏/显示主窗口