我是WPF的新手,无法找到这个问题的答案:
我有3个窗口,我想在之间导航 -
MainWindow -> Window1 -> Window2
在cancel
按钮上单击Window2我想返回Window1。
我发现这段代码可以在2个窗口之间导航,但不能在3个窗口之间导航:
主窗口:
private void Window1_Click(object sender, RoutedEventArgs e)
{
Window1 window1 = new Window1();
window1.Show();
this.Hide();
}
窗口1:
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();
}
窗口2:
private void btn_Cancel_Click(object sender, RoutedEventArgs e)
{
this.Close();
//what should I write to show Window1 again?
}
答案 0 :(得分:3)
以下是一个包含一堆导航窗口的导航服务类的示例。
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;
}
}
您可以在观看中使用它&#39;代码背后:
public void OnNextClicked(object sender, EventArgs args)
{
NavigationService.NavigateTo(new Window2());
}
public void OnPreviousClicked(object sender, EventArgs args)
{
NavigationService.NavigateBack();
}
静态构造函数将从App.xaml StartupUri开始的主视图添加到导航堆栈作为初始视图。
如果您的应用程序日益复杂,您还可以查看prism navigation system等工具。
答案 1 :(得分:0)
更改您显示窗口的方式:
private void Window1_Click(object sender, RoutedEventArgs e)
{
Hide();
new Window1().ShowDialog();
ShowDialog();
}
使用DialogResult
属性隐藏窗口(主窗口除外):
private void btn_Cancel_Click(object sender, RoutedEventArgs e)
{
DialogResult = false;
}