E_learner
E_learner

Reputation: 3582

Navigating from one xaml to another in WPF

Despite the fact that I am totally a fresh to WPF, I need to write a code, in which after I click a button, the application should open another xaml. After searching on the web, I did in in the following way:

1.I created two xaml files, namely 'Window1.xaml' and 'Window2.xaml'.

2.In my 'App.xaml' file, I let:

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

3.Then in my 'Window1.xaml', I created a button:

<Button Name="Button" Click="Button_Click_1" MouseEnter="Button_MouseEnter_1" IsDefault="True"
        HorizontalAlignment="Center" VerticalAlignment="Center">
    Start
</Button>

4.In my "Windwo1.xaml.cs" file, I created these two functions:

    private void Button_Click_1(object sender, RoutedEventArgs e)
    { 
    }

    private void Button_MouseEnter_1(object sender, MouseEventArgs e)
    {
    }

5.Then for opening "Window2.xaml" after clicking the button, I changed to:

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

But this gives me error, saying the service is null, and the program crashed. I didn't figure out any way to solve this. Any suggestions? Thanks.

Upvotes: 2

Views: 9423

Answers (2)

Eugene Podskal
Eugene Podskal

Reputation: 10401

NavigationService could not be used in classic WPF desktop application that use the Window class http://msdn.microsoft.com/en-us/library/ms750478(v=vs.110).aspx.

You could navigate between Page class instances but not between Window class instances.

You have to show and hide it manually using such techniques as shown in WPF. How hide/show main window from another window

Upvotes: 2

Nikita B
Nikita B

Reputation: 3333

Try this:

private void Button_Click_1(object sender, RoutedEventArgs e)
{ 
    var window = new Window2();
    window.ShowDialog();
}

You should also read the documentation on NavigationService class and its methods to avoid further confusion on what this class does. Here is a good place to start: http://msdn.microsoft.com/en-us/library/system.windows.navigation.navigationservice.getnavigationservice%28v=vs.110%29.aspx

Upvotes: 6

Related Questions