两个用户控件(一个包含另一个)与 MVVM 之间的通信 [英] Communication between two user controls (one contains the other) with MVVM

查看:82
本文介绍了两个用户控件(一个包含另一个)与 MVVM 之间的通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 MVVM、.NET Framework 4.6.1 和 C# 开发 WPF.

I'm developing a WPF with MVVM, .NET Framework 4.6.1 and C#.

我有两个用户控制器,一个在另一个里面:

I have two user controlers, one inside the other one:

<Grid x:Name="gridStartBatch" Margin="30" Grid.RowSpan="6" Grid.ColumnSpan="3" Visibility="{Binding GridStartBatchVisibility}">
    <local:StartBatch x:Name="userControlStartBatch" />
</Grid>

我显示 StartBatch 用户控件正在更改 GridStartBatchVisibility 值.

I show StartBatch user control changing GridStartBatchVisibility value.

StartBatchViewModel 我有三个属性要传递给 FirstControlViewModel 并且我想通知 FirstControlViewModel 更改 GridStartBatchVisibility 隐藏 StartBatch 的值.

On StartBatchViewModel I have three properties that I want to pass to FirstControlViewModel and also I want to notify FirstControlViewModel to change GridStartBatchVisibility value to hide StartBatch.

无论如何都可以从 StartBatchViewModel 访问 FirstControlViewModel 吗?

Is there anyway to access FirstControlViewModel from StartBatchViewModel?

推荐答案

有很多方法可以在视图模型和很多点之间进行交流,什么点是最好的.你可以看到它是如何完成的:

There are many ways to communicate between view models and a lot of points what the point is the best. You can see how it is done:

在棱镜中

来自 Caliburn

在我看来,最好的方法是使用 Prism 框架的 EventAggregator 模式.Prism 简化了 MVVM 模式.但是,如果你没有使用过 Prism,你可以使用 Rachel Lim 的教程 - Rachel Lim 的 EventAggregator 模式的简化版本.我强烈推荐你使用 Rachel Lim 的方法.

In my view, the best approach is using EventAggregator pattern of Prism framework. The Prism simplifies MVVM pattern. However, if you have not used Prism, you can use Rachel Lim's tutorial - simplified version of EventAggregator pattern by Rachel Lim. I highly recommend you Rachel Lim's approach.

如果您使用 Rachel Lim 的教程,那么您应该创建一个通用类:

If you use Rachel Lim's tutorial, then you should create a common class:

public static class EventSystem
{...Here Publish and Subscribe methods to event...}

并将事件发布到您的 OptionViewModel 中:

And publish an event into your OptionViewModel:

eventAggregator.GetEvent<ChangeStockEvent>().Publish(
new TickerSymbolSelectedMessage{ StockSymbol = "STOCK0" });

然后你在另一个 MainViewModel 的构造函数中订阅一个事件:

then you subscribe in constructor of another your MainViewModel to an event:

eventAggregator.GetEvent<ChangeStockEvent>().Subscribe(ShowNews);

public void ShowNews(TickerSymbolSelectedMessage msg)
{
   // Handle Event
}

Rachel Lim 的简化方法是我见过的最好的方法.但是,如果你想创建一个大的应用程序,那么你应该阅读这个文章作者:Magnus MontinCSharpcorner 示例.

The Rachel Lim's simplified approach is the best approach that I've ever seen. However, if you want to create a big application, then you should read this article by Magnus Montin and at CSharpcorner with an example.

这篇关于两个用户控件(一个包含另一个)与 MVVM 之间的通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆