【问题标题】:How to reference a window that is already open and call a method from its code behind如何引用已经打开的窗口并从其后面的代码中调用方法
【发布时间】:2023-12-31 20:13:01
【问题描述】:

我有一个非静态类MainWindow,它包含两个非静态方法ShowAskAQuestionDialog()ShowTechSupportForum()。我从MainWindow 实例打开的另一个窗口调用这些方法。如何使用MainWindow 的这个实例来调用这两个方法?我试过这样做......

            MainWindow mainWindow = (MainWindow)this.Owner;
            mainWindow.ShowAskAQuestionDialog();

但我猜 MainWindow 实际上并不是从它打开的新窗口的所有者。

有没有办法引用MainWindow 的那个实例?

我知道我可以做一些与 LINQ 相关的事情,比如

var windows = Application.Current.Windows
                                 .OfType<Window>()
                                 .Where(x => x.GetType() != typeof(MainWindow)

但我希望有像this.Parentthis.Previous 这样的东西,不可能同时选择MainWindow 的流浪实例

【问题讨论】:

  • 您可以创建一个包含窗口实例的公共属性,并使用它调用您的方法。
  • 为了做到这一点按照您尝试的方式,您只需在不同的窗口上设置.Owner 属性。
  • 我同意上面的罗德里戈......这将是最简单的事情

标签: c# .net wpf non-static


【解决方案1】:

如果MainWindow是您的启动窗口,您可以使用Application.Current.MainWindow获取它。

由于 MainWindow 将返回 Window 的实例,因此您需要将其类型转换回 MainWindow:

MainWindow window = (MainWindow)Application.Current.MainWindow;

【讨论】:

    【解决方案2】:

    在 MainWindow 上创建一个名为 Instance 的静态变量,在构造函数中设置它。现在你已经掌握了它。

    private static MainWindow _instance;
    
    public static Instance
    {
       get{  return _instance; }
    }
    

    在MainWindow的构造函数中,添加:

    _instance = this;
    

    【讨论】:

      最近更新 更多