Sending an event between two WPF windows

I have two windows WPF. One of them is the main window, and the other is the configuration window. I would like the configuration window to send an event to the main window. Any idea how I will accomplish this?

This is how I create and open the configuration window:

private void MenuItem_Click(object sender, RoutedEventArgs e) { ConfigPage Confwin= new ConfigPage(); Confwin.Owner = this; Confwin.Show(); } 
+6
source share
2 answers

You can define any event in the class of the child window and subscribe to it before showing the window.

Main window

 public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); this.Loaded += new RoutedEventHandler(MainWindow_Loaded); } void MainWindow_Loaded(object sender, RoutedEventArgs e) { Child childWindow = new Child(); childWindow.MyEvent += new EventHandler(childWindow_MyEvent); childWindow.ShowDialog(); } void childWindow_MyEvent(object sender, EventArgs e) { // handle event MessageBox.Show("Handle"); } } 

child window

 public partial class Child : Window { // define event public event EventHandler MyEvent; protected void OnMyEvent() { if (this.MyEvent != null) this.MyEvent(this, EventArgs.Empty); } public Child() { InitializeComponent(); this.Loaded += new RoutedEventHandler(Child_Loaded); } void Child_Loaded(object sender, RoutedEventArgs e) { // call event this.OnMyEvent(); } } 
+15
source

You should use the "Weak Case" template. It is built in if you use Prism or MVVMLight .

Otherwise, you will have to implement it yourself: msdn

The reason for this is that it separates the configuration window from the main window.
They do not need to know about each other so that the configuration window is reused (and any object living in your application can also listen to the event).

+2
source

Source: https://habr.com/ru/post/900117/


All Articles