在WPF中,子窗口可以通过以下几种方式调用主窗口的方法:
MainWindow mainWindow = this.Owner as MainWindow; if (mainWindow != null) { mainWindow.MyMethod(); }
MainWindow mainWindow = Application.Current.MainWindow as MainWindow; if (mainWindow != null) { mainWindow.MyMethod(); }
在主窗口中定义委托和方法:
public delegate void MyMethodDelegate(); public void MyMethod() { // 执行需要的操作 }
在子窗口中实例化委托并调用:
MyMethodDelegate methodDelegate = new MyMethodDelegate((Owner as MainWindow).MyMethod); methodDelegate.Invoke();
注意:以上方法中,前两种方式都是通过获取到主窗口的实例,然后直接调用方法。而第三种方式是通过委托实现子窗口和主窗口之间的通信。根据具体情况选择合适的方式。