c# - 如何从 App.xaml.cs 导航到其他页面?
问题描述
所以我的应用程序中有不同的页面。由于我想要一个跨越所有这些页面的菜单栏,我在我的 App.xaml 中进行了以下操作。
我通常会使用 NavigationService 在不同页面之间导航。但是如何从我的 App.xaml.cs 导航到不同的页面。
<Application.Resources>
<Menu x:Key="Menu">
<DockPanel VerticalAlignment="Top">
<Menu DockPanel.Dock="Top" FontSize="14">
<MenuItem Header="_File">
<Separator />
<MenuItem Header="_Exit" />
</MenuItem>
<MenuItem Header="_Statussen" Click="MenuItem_OnClick"/>
<MenuItem Header="_TipsTricks" />
</Menu>
</DockPanel>
</Menu>
</Application.Resources>
我在 menuitem 上获得了 StatussenPage.xaml 等页面,单击它应该显示该页面等。
向我的 App.xaml.cs 添加了以下代码:
Page testpage = new TipsTricksPage();
private void MenuItem_OnClick(object sender, RoutedEventArgs e)
{
testpage.NavigationService.Navigate(new TipsTricksPage());
}
并得到以下错误:System.NullReferenceException
解决方案
在最佳实践中,您应该使用 MainWindow 启动您的应用程序。
在 App.xaml 中
<Application x:Class="projectname.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Banc_Suspension_SAHD"
StartupURI="MainWindow.xaml.cs" // Right here !
Exit="App_Exit">
然后,在您的 MainWindow 中(在应用程序启动时直接打开),您可以创建一个菜单并在 MainWindow.cs 中处理单击事件。
在 MainWindow.Xaml.cs
<Window x:Class="projectname.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid>
<Menu>
<MenuItem Header="Re-Impression PV">
<MenuItem Click = "MyActionClick"></MenuItem>
<MenuItem></MenuItem>
</MenuItem>
<Menu/>
</Grid>
</Window>
在 MainWindow.cs
private void MyActionClick(object sender, RoutedEventArgs e)
{
//Your code
}
推荐阅读
- javascript - Div 有不同的高度,它们从哪里继承高度?
- node.js - 为什么 Chrome 不在生产中设置 cookie
- html - 防止无序列表引起的“换行符”
- javascript - React @redux/toolkit 在状态更新时不会重新渲染组件
- dynamics-crm - Dynamics crm + 插件代码,用于跨实体集合存储总和公式
- sql - SQL/Presto:如何在 ds 上获取项目开始时间的累积总和
- flutter - 在 Flutter 中初始化堆上的 State 属性与 initState 函数
- python - 尝试在 Selenium 中设置窗口,而不是我将它们选项卡到 1 个浏览器窗口中
- node.js - Mocha:无法在另一个测试文件中已经需要的文件中存根函数
- python - 在父项目上运行 pytest 时,如何忽略 git 子模块(例如 submodule/conftest.py)根目录下的 conftest.py 文件?