Je suis nouveau sur WPF et je n’ai pas trouvé de réponse à ce problème:
J’ai 3 fenêtres je veux naviguer entre MainWindow -> Window1 -> Window2
Sur le bouton cancel
cliquez sur Window2 Je veux retourner à Window1.
J’ai trouvé ce code pour naviguer entre 2 fenêtres, mais pas entre 3 car j’en ai besoin:
Fenêtre principale:
private void Window1_Click(object sender, RoutedEventArgs e) { Window1 window1 = new Window1(); window1.Show(); this.Hide(); }
Window1:
private void btn_Cancel_Click(object sender, RoutedEventArgs e) { Application.Current.MainWindow.Show(); this.Close(); } private void btn_Window2_Click(object sender, RoutedEventArgs e) { Window2 window2 = new Window2(); window2 .Show(); this.Hide(); }
Window2:
private void btn_Cancel_Click(object sender, RoutedEventArgs e) { this.Close(); //what should I write to show Window1 again? }
Changez la façon dont vous affichez vos fenêtres comme ceci:
private void Window1_Click(object sender, RoutedEventArgs e) { Hide(); new Window1().ShowDialog(); ShowDialog(); }
Et utilisez la propriété DialogResult
pour masquer vos fenêtres (sauf la fenêtre principale):
private void btn_Cancel_Click(object sender, RoutedEventArgs e) { DialogResult = false; }
Voici un exemple de classe de service de navigation contenant une stack de fenêtres parcourues.
public static class NavigationService { static NavigationService() { NavigationStack.Push(Application.Current.MainWindow); } private static readonly Stack NavigationStack = new Stack (); 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; } }
Vous pouvez l’utiliser depuis le code de vos vues derrière:
public void OnNextClicked(object sender, EventArgs args) { NavigationService.NavigateTo(new Window2()); } public void OnPreviousClicked(object sender, EventArgs args) { NavigationService.NavigateBack(); }
Le constructeur statique ajoute la vue principale démarrée à partir de votre App.xaml StartupUri à la stack de navigation comme vue initiale.
Si la complexité de votre application augmente, vous pouvez également consulter des outils tels que le système de navigation par prismes .