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 SelectionChanged
that you would have wired up with code-behind in MVVMLight is EventToCommand
which 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: EventToCommand
is 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 how EventToCommand
works because there are lots of ways to use it.
But here is the bare-bones version:
<controls:PivotItem Name="pivotItem">
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<cmd:EventToCommand Command="{Binding SelectServiceCommand}"
CommandParameter="{Binding SelectedIndex, ElementName=pivotItem}"/>
</i:EventTrigger>
<!-- other stuff -->
</i:Interaction.Triggers>
</controls:PivotItem>
and to make this work the SelectServiceCommand
has 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With