简体   繁体   中英

Navigation between pages in WPF?

I have my WPF application and my button is on a WINDOW that I added and I want the button to open a PAGE when I click it.

NavigationService nav = NavigationService.GetNavigationService(this); 
nav.Navigate(new Uri("xamlFeedbackPage.xaml", UriKind.RelativeOrAbsolute));

I have tried that code that was online and my application crashes when I click the button.

Any help?

Take a look at this post and this MSDN article . They contain explanation about what kind of Types are suitable for navigation (pages) and in which container to host them (basically a Frame). Then you should have some succes.

EDIT

Take a look at this extensive example and things will become clear.

    public PageFunction1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        NavigationService nav = NavigationService.GetNavigationService(this);
        nav.Navigate(new Uri("page2.xaml",UriKind.RelativeOrAbsolute));
    }

No need of call anything in the code.Since it can be done with xaml itself.

App.xaml

        <Application x:Class="WpfApplication1.App"
                     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                     StartupUri="Page1.xaml">
        </Application>

Page1

        <Page x:Class="WpfApplication1.Page1"
              xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
              Title="Page1">
            <StackPanel>
                <TextBlock>
                    Go to <Hyperlink NavigateUri="Page2.xaml"> Page 2 </Hyperlink>
                </TextBlock>
            </StackPanel>
        </Page>

Navigate sample

Page 2

        <Page x:Class="WpfApplication1.Page2"
              xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
              Title="Page2"> 
            <StackPanel>
                <TextBlock Margin="10">Welcome to Page2.</TextBlock>
                <TextBlock Margin="10">
                    Go back to <Hyperlink NavigateUri="Page1.xaml"> Page 1 </Hyperlink>
                </TextBlock>
            </StackPanel>
        </Page>

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