溫馨提示×

如何在C#中實現(xiàn)子窗口間的通信

c#
小樊
99
2024-09-04 16:02:41
欄目: 編程語言

在C#中,子窗口間的通信可以通過多種方式實現(xiàn)

  1. 使用事件和委托:

首先,在子窗口(ChildWindow)中定義一個事件(Event)和委托(Delegate)。然后,在主窗口(MainWindow)中注冊這個事件。當(dāng)子窗口需要與主窗口通信時,觸發(fā)這個事件。主窗口接收到事件后,可以執(zhí)行相應(yīng)的操作。

示例代碼:

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類)來實現(xiàn)子窗口間的通信。首先,在子窗口的ViewModel中發(fā)送消息。然后,在主窗口的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}");
        });
    }
}

這兩種方法都可以實現(xiàn)子窗口間的通信。你可以根據(jù)項目需求和個人喜好選擇合適的方法。

0