ViewModel之间是否可以进行通信?

3
例如,从新闻列表页面移到详细新闻页面。我能传递选定的新闻列表项到详细页面吗?在newsListViewModel中。
NewsDetailVm.SelectedNews = SelectedNews;

在新闻列表页中

await Navigation.PushAsync(new NewsDetailPage());

或者我只需要处理页面本身吗?该如何处理呢?
await Navigation.PushAsync(new NewsDetailPage(e.Item as News));

1
我一定会考虑使用依赖注入,因为它会为您处理许多基础代码,并使此类决策更加容易。如果您自己实例化视图模型,则应用程序将变得更加脆弱且难以测试。在这种情况下,我会考虑使用解耦的 pub/sub 方法。 - Charleh
1个回答

2
你可以通过一个提供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 所说的那样,这是非常耦合的方式。 如果你需要一种更松散的方式来实现你的ViewModels,我没有使用 Pub Sub,但 here 是一个 UWP MVVM Pub Sub 教程。

3
听起来这种方式耦合度很高,我建议考虑使用发布/订阅系统。 - Charleh
1
是的,它非常耦合,但在Xamarin/UWP应用中,我没有看到过Pub/Sub实现。我使用工厂,因为在大多数情况下页面是耦合的。但如果你能发一个 Pub/Sub 的例子给我看就太好了 =) - FoldFence
2
https://developer.xamarin.com/guides/xamarin-forms/messaging-center/ 我刚刚谷歌搜索了一下,看起来很相关... - Charleh
1
谢谢,看起来很有趣,我想我会去看看它。 - FoldFence

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接