MVVM - 在视图之间导航
我有一个绑定到 ViewModel 的 ListBox,该 ViewModel 公开 ObservableCollection 类型的参数。我设置了一个 ICommand,当选择 ListBox 中的某一行时会触发该 ICommand。 (使用此 post - 顺便说一句,它效果很好)。
现在我的问题(与上述方法 3 或 ListBox 无关)是当我的 ICommand 被触发时,我想要做的是导航到不同的页面(例如:详细信息页面),逻辑存储在哪里(或我该怎么做?)。
我问的原因是我不确定如何在 ViewModel 类中设置命令方法以使其保持可测试性。
ps:我正在使用 Prism,并且还想知道它是否提供任何用于导航的类/模式。
I have a ListBox that is bound to a ViewModel that exposes a parameter of type ObservableCollection. I have setup an ICommand that gets fired when one of the rows in the ListBox is selected. (using method 3 in this post - it works great by the way).
Now my question (which has nothing to do with method 3 described above or the ListBox) is when my ICommand is fired and what I want to do is navigate to a different page (eg: details page), where is the logic stored (or how do I do it?).
The reason I ask is that I am not sure how to setup the command method in the ViewModel class such that it remains testable.
ps: I am using Prism and was also wondering if it provides any classes/patterns for Navigation.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只是为了详细说明 IEventAggregator 的使用 - 它为您提供了一个简单的 Pub/Sub 模型,用于在应用程序的解耦部分(即不需要了解其他部分)之间发送任意消息。因此,我们可以在 ViewModel 构造函数中获取对
IEventAggregator
的引用(框架会自动为您解析),即:然后在我们的选择更改处理程序中,我们可以发布事件:
这依赖于我们的自定义事件类
MyListboxChangedEvent
:最后,在响应此操作的ViewModel中,我们设置了对该事件的订阅,以及相应的处理程序方法:
看起来像是很多胶水,但它变成了逻辑将 UI 的不同部分连接在一起的方法,很快就会成为第二天性。
Just to elaborate on the use of
IEventAggregator
- it gives you a simple Pub/Sub model for sending arbitrary messages between decoupled (ie neither needs to know anything about the other) parts of the application. So we can get a reference to theIEventAggregator
in our ViewModel constructor (this is automatically resolved for you by the framework) ie:Then in our selection changed handler, we can publish the event:
This relies on our custom event class
MyListboxChangedEvent
:So finally, in the ViewModel which responds to this action, we set up a subscription to the event, and corresponding handler method:
Seems like a lot of glue, but it becomes a logical method for wiring the different parts of the UI together, and it becomes second nature pretty quickly.
您是否考虑过使用 EventAggregator 来发送您想要显示不同视图的消息。 PRISM 发行版中包含的 StockTrader 应用程序将提供一个很好的使用示例。
Have you considered using the EventAggregator to send the message that you want to show a different view. The StockTrader application included in the PRISM distribution will provide a good example of the use.