How to communicate between two windows in WPF?

You can achieve communication between two windows in WPF using the following methods:

  1. Passing data through constructors: In the constructor of one window, you can pass an instance of another window as a parameter, and then retrieve the necessary data from that parameter.
public partial class MainWindow : Window
{
    private SecondWindow secondWindow;

    public MainWindow()
    {
        InitializeComponent();
        
        // 创建第二个窗口实例
        secondWindow = new SecondWindow(this);
    }

    // 在第二个窗口中,可以获取到主窗口的实例,并访问其公共属性或方法
    public void SendMessage(string message)
    {
        // 处理消息
    }
}
  1. By using events and delegates: you can define an event in one window to trigger when communicating with another window, passing data. In the other window, subscribe to the event and handle the data.
public partial class MainWindow : Window
{
    // 定义事件
    public event Action<string> MessageSent;

    private void SendMessage(string message)
    {
        // 触发事件
        MessageSent?.Invoke(message);
    }
}

public partial class SecondWindow : Window
{
    public SecondWindow()
    {
        InitializeComponent();
        
        // 订阅事件
        var mainWindow = Application.Current.Windows.OfType<MainWindow>().FirstOrDefault();
        if (mainWindow != null)
        {
            mainWindow.MessageSent += HandleMessage;
        }
    }

    private void HandleMessage(string message)
    {
        // 处理消息
    }
}
  1. Using global variables: You can define a static property or field in the App class of the application to store data that needs to be shared. Communication between two windows can be done by accessing this global variable.
public partial class App : Application
{
    // 全局变量
    public static string SharedMessage { get; set; }
}

public partial class MainWindow : Window
{
    private void SendMessage(string message)
    {
        // 设置全局变量的值
        App.SharedMessage = message;
    }
}

public partial class SecondWindow : Window
{
    public SecondWindow()
    {
        InitializeComponent();
        
        // 获取全局变量的值
        var message = App.SharedMessage;
        
        // 处理消息
    }
}

Here are some common implementation methods, you can choose the one that best suits your situation.

bannerAds