【问题标题】:How to refer to current open window in WPF如何在 WPF 中引用当前打开的窗口
【发布时间】:2017-09-19 21:36:20
【问题描述】:

我弹出了一个窗口,如果 MainWindow 尚不存在,则会创建一个 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;
    }

如何引用 MainWindow 以便在 if 语句之外使用它?

我希望能够做到main.txbox.Text = .... 等。

这是我尝试过的:

MainWindow main;
if 
{...
}
else
{...
}
main= App.Current.MainWindow;

MainWindow main = App.Current.MainWindow();

这些方法似乎都不起作用。我确定这真的很简单,我只是无法弄清楚语法。帮忙?

编辑:类似于我之前问过的this question,但不同的是,这里我在引用当前打开的窗口时询问语法。类似的问题是指如何检测打开了哪个窗口。它们很相似,但我不想跑题。

【问题讨论】:

  • 请继续您提出的问题here
  • 直接写入另一个窗口控件(例如文本框)是非常糟糕的主意。最好通过绑定属性来做到这一点。
  • @Muds 为新的疑问发布新问题非常好。有助于保持其他问题不跑题。

标签: c# wpf


【解决方案1】:

试试这个方法

 var window = Application.Current.Windows.OfType<Window>().SingleOrDefault(w => w.IsActive);

【讨论】:

    【解决方案2】:

    在某些基类或 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;
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-13
      • 1970-01-01
      • 2016-07-02
      • 2023-01-12
      相关资源
      最近更新 更多