Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
180 views
in Technique[技术] by (71.8m points)

c# - Sending event between 2 WPF windows

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();
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...