Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to navigate to other page with button in WPF

Tags:

c#

button

wpf

xaml

I have a second .xaml page set up under the name Page2.xaml and I want to make it so that when my button is clicked, the user is taken to Page2.xaml

I have this for my button inside of my Page1.xaml:

<Grid>
    <Button x:Name="localModeBtn" 
            Style="{StaticResource MainButtonStyle}"  
            Content="local mode" 
            Click="localModeBtn_Click" />
</Grid>

And for the button event handler:

private void localModeBtn_Click(object sender, RoutedEventArgs e)
    {
        Uri uri = new Uri("Page2.xaml", UriKind.Relative);
        this.NavigationService.Navigate(uri);
    }

Upon clicking the button I receive an error that says "Cannot locate resource page2.xaml" The thing is that Page2.xaml is in the same folder as Pag1.xaml so I can't see where I've gone wrong?

like image 308
Jake Avatar asked Dec 26 '13 16:12

Jake


People also ask

How do I navigate to another page in WPF?

To package content for navigation, WPF provides the Page class. You can navigate from one Page to another declaratively, by using a Hyperlink, or programmatically, by using the NavigationService. WPF uses the journal to remember pages that have been navigated from and to navigate back to them.

How do I add a page in WPF?

Step 1: Create an empty WPF using Visual Studio, enter the name for the application and click on OK. Step 2: Create a button using the following code or drag and drop a button from the ToolBox of Visual Studio 2013.


1 Answers

Solution to my own question:

I feel a bit silly providing a solution to my own question but thanks to Jasti's link I was able to sort my code out. As he had only posted a comment, I can't mark it as an answer, so here is the solution.

I changed the NavigationWindow to a Window and inserted:

<DockPanel>
    <Frame x:Name="_NavigationFrame" NavigationUIVisibility="Hidden" />
</DockPanel>

And within the constructor of the MainWindow.xaml.cs I added:

_NavigationFrame.Navigate(new Page1());

Then the last step was to adjust the button event handler to:

this.NavigationService.Navigate(new Uri("Pages/Page2.xaml", UriKind.Relative));
like image 96
Jake Avatar answered Sep 20 '22 15:09

Jake