Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending event between 2 WPF windows

Tags:

c#

events

wpf

I have two WPF windows. One is the main window and the other is some configuration window. I would like the configuration window to send and event to the main window. Any idea how I an accomplish it?

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();
    }
like image 947
MoShe Avatar asked Oct 26 '11 09:10

MoShe


2 Answers

You can define any event in your child window class 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();
    }
}
like image 171
Samich Avatar answered Sep 20 '22 13:09

Samich


You should use the Weak Event pattern. It is built in if you use Prism or MVVMLight.

Otherwise, you'll have to implement it yourself: msdn

The reason for this, is that it decouples the configuration window from the main window.
They shouldn't know about each other so that the configuration window is reusable (and any object alive in your app can listen to the event as well).

like image 25
Louis Kottmann Avatar answered Sep 19 '22 13:09

Louis Kottmann