简体   繁体   English

从另一个 window 访问 MainWindow

[英]Accessing MainWindow from another window

I have created a new Window that opens up from the MainWindow.我创建了一个从 MainWindow 打开的新 Window。 Upon clicking a button from this Window, the Window should close and at the same time trigger some event in MainWindow.单击此 Window 中的按钮后,Window 应关闭并同时在 MainWindow 中触发某些事件。

I thought this would be easy to implement but I don't know how to access MainWindow methods & fields from another Window...我认为这很容易实现,但我不知道如何从另一个 Window 访问 MainWindow 方法和字段......

Any help would be appreciated.任何帮助,将不胜感激。 Thanks: :)谢谢: :)

That is the wrong way to do it... the child window should have a Closed event that you can register a handler for.这是错误的做法......孩子 window 应该有一个Closed事件,您可以为其注册一个处理程序。 If you really need to execute parent window functions from the child before it has closed then you can pass delegates in to the child when you open it.如果您确实需要在子程序关闭之前从子程序执行父 window 函数,那么您可以在打开子程序时将代表传递给子程序。

You dont need to do that in this way...你不需要以这种方式这样做......

define in the child window an event like:在子 window 中定义如下事件:

public event EventHandler Closing;

when you create this window in the main window subscribe to it:当您在主 window 中创建此 window 时,请订阅它:

Window1 wnd = new Window1();

wnd.Closing += new EventHandler(childClosing);

when closing the child window check if the event is subscribed and raise it:当关闭子 window 检查事件是否被订阅并引发它:

if (Closing != null) {
  Closing(this, new EventArgs());
}

of course you need a childClosing method in the main window:当然你需要在主 window 中使用 childClosing 方法:

private void childClosing(object sender, EvenrArgs e) {
  /// do your work
}

If you need to pass some data back then you create a class that derives from EvenrArgs and use that instead.如果您需要传回一些数据,则创建一个派生自 EvenrArgs 的 class 并使用它。 But you need a delegate different from Eventhandler like:但是您需要一个不同于 Eventhandler 的委托,例如:

class ClosingArgs : EventArgs {
   // some property here
}

in the child window在孩子 window

delegate void ClosingEventHandler(object sender, ClosingArgs e);

and

public event ClosingEventHandler Closing;

cheers!干杯!

This is quite simple since you want an action in the MainWindow to be triggered when the child window closes, simply register the close event:这非常简单,因为您希望在子 window 关闭时触发 MainWindow 中的操作,只需注册关闭事件:

// In the main window, whenever your start your child window (not in the constructor)
private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        var window = new Window();
        window.Closed += new EventHandler(window_Closed);
        window.ShowDialog();
    }

    void window_Closed(object sender, EventArgs e)
    {
        throw new NotImplementedException();
    }

Then the function window_Closed in the main window will be called when the child window is closed.然后当子 window 关闭时,将调用主 window 中的 function window_Closed。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM