I\'m new to WPF and couldn\'t find an answer to to this issue:
I have 3 windows I want to navigate between-
MainWindow -> Window1 -> Window2
Change the way you show your windows like this:
private void Window1_Click(object sender, RoutedEventArgs e)
{
Hide();
new Window1().ShowDialog();
ShowDialog();
}
And use the DialogResult
property to hide your windows (except the main window):
private void btn_Cancel_Click(object sender, RoutedEventArgs e)
{
DialogResult = false;
}
Here is an example of a navigation service class that holds a stack of navigated windows.
public static class NavigationService
{
static NavigationService()
{
NavigationStack.Push(Application.Current.MainWindow);
}
private static readonly Stack<Window> NavigationStack = new Stack<Window>();
public static void NavigateTo(Window win)
{
if(NavigationStack.Count > 0)
NavigationStack.Peek().Hide();
NavigationStack.Push(win);
win.Show();
}
public static bool NavigateBack()
{
if (NavigationStack.Count <= 1)
return false;
NavigationStack.Pop().Hide();
NavigationStack.Peek().Show();
return true;
}
public static bool CanNavigateBack()
{
return NavigationStack.Count > 1;
}
}
You can use it from your views' code behind :
public void OnNextClicked(object sender, EventArgs args)
{
NavigationService.NavigateTo(new Window2());
}
public void OnPreviousClicked(object sender, EventArgs args)
{
NavigationService.NavigateBack();
}
The static constructor adds the main view started from your App.xaml StartupUri to the navigation stack as the initial view.
If your application has a growing complexity you may also have a look at tools such as prism navigation system.