MVVM - 分离视图之间的通信 [英] MVVM - Communication between Separated Views

查看:38
本文介绍了MVVM - 分离视图之间的通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试弄清楚如何执行以下操作:

I'm trying to figure out how to do the following:

我有一个 CustomerListViewModel,其中包含一个 ObservableCollection

I have a CustomerListViewModel that contains a ObservableCollection<Customer>

MainView 持有这些视图的一个实例:

MainView holds an instance of these views:

  • CustomerListView - 创建 CustomerListViewModel
  • 的实例
  • SearchView - 创建和实例 SearchViewModel
  • CustomerListView - which creates an instance of CustomerListViewModel
  • SearchView - which creates and instance of SearchViewModel

我的问题是,如何将 CustomerListView 和 SearchView 分开.只有在选择了客户时才应显示 SearchView.SearchViewModel 的唯一依赖项应该是 Customer 模型.如果没有从 CustomerListViewModel 中选择 Customer,则不应显示 SearchView.

My question is, How do I keep the CustomerListView and the SearchView separated. The SearchView should only be displayed if a Customer is selected. The only dependency for the SearchViewModel should be a Customer Model. If there isn't a Customer selected from the CustomerListViewModel, then the SearchView shouldn't be displayed.

我是否应该引入一个包含 CustomerListViewModelSearchViewModel 的新 View/ViewModel,它们可以保存对 Selected Customer 的引用并切换SearchView 的显示?如果没有,我应该怎么做?

Should I introduce a new View/ViewModel that contains both a CustomerListViewModel and SearchViewModel that can hold a reference to the Selected Customer and toggle the displaying of a SearchView? If not, how should I go about this?

我知道这个问题很广泛,但我希望得到任何建议.

I know this question is pretty broad, but I would appreciate any suggestions.

推荐答案

不要让 MainView 包含 CustomerListView 和 SearchView 的实例.他们三个应该是分开的.

Don't make MainView contain instances of CustomerListView and SearchView. All three of them should be separate.

就视图之间的通信而言,这应该通过各自的视图模型使用例如 mvvm-light messenger 来完成.如果您为每个视图注册不同的信使,那么您可以从视图模型向您想要的任何视图发送消息.

As far as the communication between views is concerned, this should be done through the respective viewmodel using e.g mvvm-light messenger. If you register a different messenger with each view, then from a viewmodel you can send message to any view you want.

只是使用 MVVMLight Messenger 的简单示例:-

Just an example of the simplicity of using an MVVMLight Messenger:-

查看:

Messenger.Default.Register<NotificationMessage>(this, OpenViewMessageReceived);

private void OpenViewMessageReceived(NotificationMessage msg)
{
    //Logic 
}

视图模型:

Messenger.Default.Send(new NotificationMessage(someStr));

这篇关于MVVM - 分离视图之间的通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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