C# 如何在WPF中引用当前打开的窗口
我弹出了一个窗口,如果主窗口不存在,就会创建一个主窗口:C# 如何在WPF中引用当前打开的窗口,c#,wpf,C#,Wpf,我弹出了一个窗口,如果主窗口不存在,就会创建一个主窗口: if (App.Current.MainWindow != null && App.Current.MainWindow.GetType() == typeof(MainWindow)) { this.Close(); } else { //main Window hasn't been created yet so create it! MainWindow main = new
if (App.Current.MainWindow != null && App.Current.MainWindow.GetType() == typeof(MainWindow))
{
this.Close();
}
else
{
//main Window hasn't been created yet so create it!
MainWindow main = new MainWindow();
App.Current.MainWindow = main;
this.Close();
main.Show();
wndw = main;
}
如何引用主窗口,以便在if语句之外使用它
我想能够做main.txbox.Text=..
等
以下是我尝试过的:
MainWindow main;
if
{...
}
else
{...
}
main= App.Current.MainWindow;
或mainwindowmain=App.Current.MainWindow()代码>
这两种方法似乎都不起作用。我肯定这很简单,我就是搞不懂语法。帮忙
编辑:与我之前询问的类似,但不同,因为这里我询问的是引用当前打开的窗口时的语法。类似的问题涉及如何检测打开的窗口。它们很相似,但我不想离题。试试这种方法
var window = Application.Current.Windows.OfType<Window>().SingleOrDefault(w => w.IsActive);
var window=Application.Current.Windows.OfType().SingleOrDefault(w=>w.IsActive);
在某些基类或App.xaml.cs中创建以下内容:
public static Window ActivatedWindow {get;set;}
然后放入基类派生窗口或所有窗口的激活事件:
第一个选项-个人窗口基类:
public class MetroToolWindowBase
{
public MetroToolWindowBase()
{
Activated += new EventHandler(MakeActive);
}
private void MakeActive(object sender, EventArgs e)
{
App.ActivatedWindow= this;
}
}
第二个选项-在Windows激活的情况下:
private void XWindow_Activated(object sender,EventArgs e)
{
App.ActivatedWindow= this;
}
请继续回答您提出的问题。直接写入另一个窗口控件(例如文本框)是一个非常糟糕的主意。最好通过绑定属性来实现这一点。@Muds为新的疑问发布新的问题完全可以。有助于保持其他问题与主题无关。