首页 > 解决方案 > 如何从 WPF 中的当前页面调用另一个页面?

问题描述

我有一个简单的系统,可以在多个页面之间切换。MainWindow有一些重定向到页面的功能:

每个其他功能正在重定向到另一个页面。

private void BtnDebug_Click(object sender, RoutedEventArgs e)
{
   FrContent.Content = new Page_Debug();
}

这很好用,因为所有这些函数都是从MainWindow. 我也需要从Page上面的系统不起作用的地方给他们打电话。

这是我尝试使用的一种方式:

private readonly MainWindow _mainWindow = new MainWindow();

private void BtnShowNotes_OnClick(object sender, RoutedEventArgs e)
{
    _mainWindow.FrContent.Content = new Page_Notes();
}

问题是它没有显示 XAML 中的任何元素,尽管它调用了InitializeComponent()函数。为什么它不像函数那样起作用MainWindow

标签: c#wpfuser-interface

解决方案


您正在创建 的新实例MainWindow。您应该访问Frame已经存在的窗口。您可以使用以下Application.Current.Windows属性获得对此的引用:

private void BtnShowNotes_OnClick(object sender, RoutedEventArgs e)
{
    MainWindow mw = Application.Current.Windows.OfType<MainWindow>().FirstOrDefault();
    if (mw != null)
        mw.FrContent.Content = new Page_Notes();
}

推荐阅读