以前,我只有一个xaml
文件,这是唯一的Windows,即mainWindow
。要访问另一个类(显式为非静态类)中的任何按钮/文本框/对象,我可以像这样投射Window
mainWindow mainWin = Application.Current.Windows.Cast<Window>().FirstOrDefault(w => w is mainWindow) as mainWindow;
现在我的问题是,这对于几页如何工作,因为现在我有一个Frame
,我在其中加载了几页。实际上,它确实NOT像这样工作:
myPage page = Application.Current.Windows.Cast<Page>().FirstOrDefault(p => p is myPage) as myPage;
存在运行时错误,提示:
System.InvalidCastException:无法将类型为“ namespace.mainWindows”的对象转换为类型为“ System.Windows.Controls.Page”的对象]
使MainWindow返回显示的页面:
public class mainWindow
{
public Page GetCurrentPage()
{
// return known Page;
};
}
然后:
mainWindow mainWin = Application.Current.Windows.OfType<mainWindow>().FirstOrDefault();
Page p = mainWin?.GetCurrentPage();