c#

如何在C#中实现子窗口间的通信

小樊
101
2024-09-04 16:02:41
栏目: 编程语言

在C#中,子窗口间的通信可以通过多种方式实现

  1. 使用事件和委托:

首先,在子窗口(ChildWindow)中定义一个事件(Event)和委托(Delegate)。然后,在主窗口(MainWindow)中注册这个事件。当子窗口需要与主窗口通信时,触发这个事件。主窗口接收到事件后,可以执行相应的操作。

示例代码:

ChildWindow.cs:

public partial class ChildWindow : Window
{
    public delegate void MessageEventHandler(object sender, MessageEventArgs e);
    public event MessageEventHandler MessageReceived;

    public ChildWindow()
    {
        InitializeComponent();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        string message = "Hello from ChildWindow!";
        MessageReceived?.Invoke(this, new MessageEventArgs(message));
    }
}

public class MessageEventArgs : EventArgs
{
    public string Message { get; set; }

    public MessageEventArgs(string message)
    {
        Message = message;
    }
}

MainWindow.xaml.cs:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void OpenChildWindow_Click(object sender, RoutedEventArgs e)
    {
        ChildWindow childWindow = new ChildWindow();
        childWindow.MessageReceived += ChildWindow_MessageReceived;
        childWindow.Show();
    }

    private void ChildWindow_MessageReceived(object sender, MessageEventArgs e)
    {
        MessageBox.Show($"Message from ChildWindow: {e.Message}");
    }
}
  1. 使用MVVM模式和消息传递库(如Messenger):

在MVVM模式中,我们可以使用消息传递库(如MvvmLight的Messenger类)来实现子窗口间的通信。首先,在子窗口的ViewModel中发送消息。然后,在主窗口的ViewModel中注册接收消息。

安装MvvmLight库:

Install-Package MvvmLightLibs

ChildViewModel.cs:

public class ChildViewModel : ViewModelBase
{
    public RelayCommand SendMessageCommand { get; private set; }

    public ChildViewModel()
    {
        SendMessageCommand = new RelayCommand(SendMessage);
    }

    private void SendMessage()
    {
        Messenger.Default.Send<string>("Hello from ChildWindow!");
    }
}

MainViewModel.cs:

public class MainViewModel : ViewModelBase
{
    public MainViewModel()
    {
        Messenger.Default.Register<string>(this, message =>
        {
            MessageBox.Show($"Message from ChildWindow: {message}");
        });
    }
}

这两种方法都可以实现子窗口间的通信。你可以根据项目需求和个人喜好选择合适的方法。

0
看了该问题的人还看了