How to call method of the main WPF window from the modal window?
(In fact I want to start some timer of the MainWindow.xaml.cs when I close some model window.)
Thank you!
What you can do is before opening your second window assign the main window as its owner, then from the modal window call the Owner property, cast it into a MainWindow object and you'll be able to execute the method.
// Code in main window
ModalWindow window = new ModalWindow();
window.Owner = this;
window.ShowDialog()
//Code on the modal window
var myObject = this.Owner as MainWindow;
myObject.MyMethod(); // Call your method here.
public class ModalWindow : Window
{
private MainWindow _parent;
public ModalWindow(MainWindow parent)
{
_parent = parent;
Owner = parent;
}
void CallParent()
{
_parent.Call();
}
}
I would suggest this kind of pattern is a code smell.
If your goal is to pass information from the modal to the parent, better to expose properties on the modal window and, after it closes, read those values and perform whatever actions are necessary in the parent.
If your goal is to pass information from the parent to the modal, then pass it into the constructor or public properties before calling ShowDialog().
There are a lot of ways to do this.
You could overload the constructor of the modal window such that you can pass in a reference to that function, or the main window. Or, add a property to that window.
You could also start the timer on the next line in the main window code that shows the modal window.
If this model window will open from the MainWindow
, like this let's say
modalWindow.ShowDialog()
it's enough just to add the code after this call and it will be executed after the modal window closed.
If the modal window is opened form somewhere else but on closing should run the code on complitely unrelated part, can use, for example, Commands or RelayCommand (kind of direct delegate call).
Hope this helps.
You could attach an event handler to the "Closing" event of the modal dialog, which would be executed in the main program when the dialog fires this event.