【问题标题】:Is communication possible between ViewModels?ViewModel 之间可以通信吗?
【发布时间】:2016-10-29 02:57:36
【问题描述】:

例如,从新闻列表页面移动到详细新闻。 我可以将带有新闻列表的选定项目传递给详细信息吗? 在 newsLisViewModel 中

NewsDetailVm.SelectedNews = SelectedNews;

在新闻列表页面中

await Navigation.PushAsync(new NewsDetailPage());

还是应该只处理页面本身?

await Navigation.PushAsync(new NewsDetailPage(e.Item as News));

【问题讨论】:

  • 我肯定会考虑查看依赖注入,因为它会为您覆盖大量的管道代码,并且可以更轻松地做出这样的决定。如果您自己实例化视图模型,则应用程序将更加脆弱且难以测试。在这种情况下,我会考虑采用 pub/sub 之类的解耦方法

标签: c# mvvm xamarin viewmodel


【解决方案1】:

您可以与MainViewModel() 和提供此MainViewModel() 的单个工厂进行通信

public class MainViewModelFactory{

private static MainViewModel main{get;set;}
public static MainViewModel GetReference(){
if(main == null){
main = new MainViewModel();
return main;
}else 
   return main;
}
}

MainViewModel 具有每个其他所需 Viewmodel 的实例。

所以你可以通过MainViewModelFactory.GetReference().DoAnything();访问

你拥有的每个 ViewModel。

但就像@Charleh 所说,这是一种非常耦合的方式。我没有使用 Pub Sub,但 here 是 UWP MVVM Pub Sub 的教程,如果您需要更松散的方式来实现您的 ViewModel。

【讨论】:

  • 这听起来像是一种非常耦合的处理方式,我会考虑改用 pub/sub 系统。
  • 是的,它非常耦合,但在 Xamarin/UWP 应用程序中,我没有看到 Pub/Sub 实现我使用工厂,因为在大多数情况下页面是耦合的。但是,如果您可以发布 pub sub 的示例,我会很高兴看到它 =)
  • developer.xamarin.com/guides/xamarin-forms/messaging-center 刚刚用谷歌搜索并想出了这个,听起来很相关......
  • 谢谢它看起来很有趣,我想我会看看它。
猜你喜欢
  • 1970-01-01
  • 2015-07-11
  • 2017-03-02
  • 1970-01-01
  • 1970-01-01
  • 2015-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多