wpf 如何在WPF中引用当前打开的窗口
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31544090/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to refer to current open window in WPF
提问by hereiam
I have a window popping up, and a MainWindow is created if one doesn't exist already:
我弹出了一个窗口,如果 MainWindow 不存在,则会创建一个窗口:
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;
}
How do I refer to the MainWindow so I can use it outside the if statement?
我如何引用 MainWindow 以便我可以在 if 语句之外使用它?
I want to be able to do main.txbox.Text = ....etc.
我希望能够做main.txbox.Text = ....等。
Here's what I've tried:
这是我尝试过的:
MainWindow main;
if
{...
}
else
{...
}
main= App.Current.MainWindow;
or MainWindow main = App.Current.MainWindow();
或者 MainWindow main = App.Current.MainWindow();
Neither of these approaches seem to work. I'm sure this is really simple, I just can't figure out the syntax. Help?
这些方法似乎都不起作用。我确定这真的很简单,我只是无法弄清楚语法。帮助?
Edit: Similar to this questionI asked earlier, but different because here I'm asking about syntax when referencing the currently opened window. The similar question is referring to how to detect which window is opened. They're similar, but I didn't want to go off topic.
编辑:类似于我之前问过的这个问题,但不同,因为在这里我在引用当前打开的窗口时询问语法。类似的问题是指如何检测打开了哪个窗口。它们很相似,但我不想偏离主题。
回答by Abin
Try this way
试试这个方法
var window = Application.Current.Windows.OfType<Window>().SingleOrDefault(w => w.IsActive);
回答by Richard Aguirre
In some base class or App.xaml.cs create this:
在一些基类或 App.xaml.cs 中创建:
public static Window ActivatedWindow {get;set;}
Then put in your base class deriving Window or all of your Window's Activate Event:
然后放入派生 Window 或所有 Window 的 Activate 事件的基类:
First Option - personal Window Base Class:
第一个选项 - 个人窗口基类:
public class MetroToolWindowBase
{
public MetroToolWindowBase()
{
Activated += new EventHandler(MakeActive);
}
private void MakeActive(object sender, EventArgs e)
{
App.ActivatedWindow= this;
}
}
Second Option- In Activated Event of Windows:
第二个选项 - 在 Windows 的激活事件中:
private void XWindow_Activated(object sender,EventArgs e)
{
App.ActivatedWindow= this;
}

