简体   繁体   中英

How to navigate from App.xaml.cs to other pages?

So I have different pages in my application. Since I want a menubar across all of these pages I made the following in my App.xaml.

I would normally use NavigationService to navigated between different pages. But how do I navigate to different pages from my 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>

I got pages StatussenPage.xaml etc. on menuitem click it should show that page etc.

Added following code to my App.xaml.cs:

        Page testpage = new TipsTricksPage();

        private void MenuItem_OnClick(object sender, RoutedEventArgs e)
        {
            testpage.NavigationService.Navigate(new TipsTricksPage());
        }

And getting following error: System.NullReferenceException

In best practice, You should start your app with a MainWindow .

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

then, IN your MainWindow (open directly when app start) you can create a Menu and in the MainWindow.cs treat click event.

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

In MainWindow.cs

        private void MyActionClick(object sender, RoutedEventArgs e)
        {
            //Your code
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM