【问题标题】:Navigation between Pages and Windows in WPFWPF 中页面和窗口之间的导航
【发布时间】:2021-12-08 13:58:01
【问题描述】:

我有一个我正在尝试解决的问题。我有两个 WPF 窗口。这些窗口包含内容的页面。我的问题不是导航页面,而是窗口到窗口。下面是代码示例:

LoginPortal Design

 <Grid>
    <Frame x:Name="MainFrame" NavigationUIVisibility="Hidden"/>
</Grid>

LoginPortal Code

 public LoginPortalMain()
    {
        InitializeComponent();

        MainFrame.Navigate(new Uri("/Pages/LoginPortal.xaml", UriKind.RelativeOrAbsolute));

     
    }

这是我的登录门户,包含 4 个按钮。每个按钮都会打开包含多个页面的第二个窗口。

private void BtnSales_Click(object sender, RoutedEventArgs e)
    {
        var w = Application.Current.Windows[0];
        w.Hide();
        MainWindow mn = new MainWindow();
        mn.Content = new SalesPage();
        mn.Show();
    }

单击此按钮时,它会打开第二个 WPF 窗口,该窗口包含多个页面。导航没有问题。当我从 MainWindow 连接 Closing 事件以返回 LoginPortalMain 时,问题就开始了

    private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {
        LoginPortalMain lgm = Application.Current.MainWindow as LoginPortalMain;
        lgm.Show();
    }

然后它又回到起点。现在我的问题是如果我再次点击同一个按钮。它只是复制了一切。然后在关闭任何东西时,它只会添加新窗口。如果我随后退出任何窗口,则会在下图中引发错误。我的问题是,有没有办法在 MainWindow 关闭后处理导航。因此,一旦您第二次关闭 mainWindow,就没有重复的窗口。我以前在单个窗口上使用过导航,但在多个窗口上没有。

我可能不得不重新考虑整个结构并使用自定义 UserControls 并找出从 Pages 到 UserControls 的动画序列。但是,我们将不胜感激。

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

【问题讨论】:

    标签: c# wpf navigation


    【解决方案1】:

    如果您只想打开一个新窗口实例,请尝试显示和隐藏一个窗口实例。

    当按下打开窗口按钮时,根据需要创建窗口并显示它。

    private OtherWindow mOtherWindow;
    private void OpenWindowButtonClick(object sender, RoutedEventArgs e)
    {
        mOtherWindow ??= new OtherWindow(); //initialize child window on first call
        mOtherWindow.Show();
    }
    

    当另一个窗口关闭时隐藏它并取消关闭请求。您也可以在此处重置其他窗口状态,以便下次显示。

    private void OtherWindowClosingEvent(object sender, System.ComponentModel.CancelEventArgs e)
    {
        ((Window)sender).Hide();
        Application.Current.MainWindow.Activate();
        e.Cancel = true;
    }
    

    【讨论】:

    • 这是两个不同的窗口,不是子窗口
    • 我更新了答案中的措辞。我称它为子窗口的唯一原因是它是由另一个窗口创建的。它们是两个独立的窗口。
    • 它仍然不适用于您的解决方案。我认为一个页面只能固定到同一个窗口。它适用于第一个选择,但在第二个选择上它不会消除它只是复制它们的窗口
    • 关闭主窗口以外的窗口时是否会发生 Window_Closing 事件?图像中的异常是因为 Application.Current.MainWindow 不是 LoginPortalMain。 Application.Current.MainWindow 是什么类型的?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-25
    • 2020-08-02
    • 1970-01-01
    • 2013-10-04
    相关资源
    最近更新 更多