MVVMlight怎么实现两个窗体之间传值
时间: 2024-02-29 15:51:31 浏览: 34
在 `MVVM Light` 中,可以使用 `Messenger` 类来实现两个窗体之间的通信。`Messenger` 是 `MVVM Light` 框架提供的一种消息传递机制,它能够让不同的对象之间进行通信,而不需要相互持有引用。以下是一个示例代码,用于在两个窗体之间传递数据:
首先,在发送窗体中定义一个 `Message` 类型,并在构造函数中初始化该类型的对象:
```csharp
public class MyMessage
{
public string Data { get; set; }
}
public partial class SenderWindow : Window
{
public SenderWindow()
{
InitializeComponent();
DataContext = this;
// 初始化 Message 对象
var message = new MyMessage { Data = "Hello, World!" };
// 发送消息
Messenger.Default.Send(message);
}
}
```
然后,在接收窗体中注册 `Messenger`,并在回调方法中处理接收到的消息:
```csharp
public partial class ReceiverWindow : Window
{
public ReceiverWindow()
{
InitializeComponent();
DataContext = this;
// 注册消息接收器
Messenger.Default.Register<MyMessage>(this, OnMessageReceived);
}
private void OnMessageReceived(MyMessage message)
{
// 处理接收到的消息
MessageBox.Show(message.Data);
}
}
```
在上面的示例中,我们在发送窗体中创建了一个 `MyMessage` 对象,并通过 `Messenger` 发送了该对象。在接收窗体中,我们注册了一个接收器,用于接收 `MyMessage` 类型的消息。当发送窗体发送消息时,接收窗体中的 `OnMessageReceived` 方法会被回调,然后我们可以在该方法中处理接收到的消息。
需要注意的是,在接收窗体中注册 `Messenger` 时,需要在窗体关闭时注销接收器,以避免内存泄漏:
```csharp
protected override void OnClosed(EventArgs e)
{
Messenger.Default.Unregister<MyMessage>(this);
base.OnClosed(e);
}
```
以上是使用 `MVVM Light` 实现两个窗体之间传值的示例代码,希望能够对你有所帮助。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)