basically I have a pivot control in my WP7 app that contains 3 views. On each view I’m calling 1 of my 3 different web services that I run. What I’m trying to do is call the service only when they navigate to that particular view.
It’s pretty simple using the code behind because all you do is use selected index with a switch statement and you can fire certain methods accordingly. Any idea on how to accomplish this from a view model?
NOTE: I’m using MVVM Light.
UPDATE: Here’s my code that I would normally use:
private void PivotItem_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
int currentPivot = ResultsPivot.SelectedIndex;
switch (currentPivot)
{
case 0:
//Fire Method 1
break;
case 1:
//Fire Method 2
break;
case 2:
//Fire Method 3
break;
default:
//Fire default method
break;
}
}
The standard approach with MVVMLight is the split your view-model into data and commands. Most things you use databinding related, properties, etc. but commands actually do something.
In this case what you are calling “Fire Method 1” is an ordinary method that to conform to the pattern you have to convert to a command. If you already have commands you know what I am talking about.
The glue for events like
SelectionChangedthat you would have wired up with code-behind in MVVMLight isEventToCommandwhich is a XAML fragment that you put in the XAML with the pivot item instead of in the event hander.So this is the pattern:
EventToCommandis your key to hooking up XAML events to view-model commands without any code-behind. The best thing to do is use the MVVMLight samples to see howEventToCommandworks because there are lots of ways to use it.But here is the bare-bones version:
and to make this work the
SelectServiceCommandhas to actually exist in the view-model and it has to take a parameter and do the right thing for 0, 1, 2, 3, etc.