开发者

MVVM - navigating between views

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 ab开发者_如何转开发ove 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.


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 the IEventAggregator in our ViewModel constructor (this is automatically resolved for you by the framework) ie:

private IEventAggregator eventAggregator;

public PublisherViewModel(IEventAggregator eventAggregator)
{
    this.eventAggregator = eventAggregator;

Then in our selection changed handler, we can publish the event:

var changedEvt = eventAggregator.GetEvent<MyListboxChangedEvent>();
changedEvt.Publish(selectedItemId);

This relies on our custom event class MyListboxChangedEvent:

public class MyListboxChangedEvent : CompositePresentationEvent<int> {}

So finally, in the ViewModel which responds to this action, we set up a subscription to the event, and corresponding handler method:

public SubscriberViewModel(IEventAggregator eventAggregator)
{
    var changedEvt = eventAggregator.GetEvent<MyListboxChangedEvent>();
    changedEvt.Subscribe(OnListBoxChanged, ThreadOption.UIThread);
}

public void OnListBoxChanged(int selectionId)
{
    // do whatever we need
}

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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜