首页 > 解决方案 > 如何从 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

标签: c#wpf

解决方案


在最佳实践中,您应该使用 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
        }

推荐阅读