Saturday, April 21, 2012

Windows phone 7 : Using Page Navigation in MVVM

Microsoft provides development environment for develop windows mobile application.

To develop application in WP7, we require to install Windows Phone SDK (it includes Developer tool,Visual Studio 2010 Express for Windows Phone, Windows Phone Emulator).

Click Windows Phone SDK 7.1 to Download SDK 

When we are using MVVM pattern in WP7, navigation between pages is sticky task for developer because we don't have NavigationContext in ViewModel.

I am going to focus on how to implement Page Navigation in WP7 using MVVM.


As shown in above screen, when I click on Buy Product button it will navigate to Product Page using MVVM.

For MVVM, I have used GalaSoft.MvvmLight toolkit.

I am going to Explain step by step.

Step 1 : Create Interface that contains method for navigation.

    public interface INavigationService
    {
        void Navigate(string uri);
        void Navigate(string uri, IDictionary<string, string> parameters);
    }

Method with one string parameter will navigate page to passed Uri.

Method with two parameters will pass query string parameter with Uri and navigate to page.

Step 2 : Implements Methods of INavigationService Interface
 
 public class NavigationService : INavigationService
 {
    public void Navigate(string uri)
    {
        PhoneApplicationFrame rootFrame = Application.Current.RootVisual as PhoneApplicationFrame;
        rootFrame.Navigate(new Uri(uri, UriKind.RelativeOrAbsolute));    
    }
    public void Navigate(string uri, IDictionary<string, string> parameters)
    {
       PhoneApplicationFrame rootFrame = Application.Current.RootVisual as PhoneApplicationFrame;
       if (rootFrame != null)
       {
          StringBuilder fullUri = new StringBuilder();
          fullUri.Append(uri);
          if (parameters != null && parameters.Count > 0)
          {
              fullUri.Append("?");
              bool isAppendAmp = false;
              foreach (KeyValuePair<string, string> keyValuePair in parameters)
              {
                 if (isAppendAmp)
                 {
                            fullUri.Append("&");
                 }
                 fullUri.AppendFormat("{0}={1}", keyValuePair.Key, keyValuePair.Value);
                 isAppendAmp = true;
              }
          }
          uri = fullUri.ToString();
          rootFrame.Navigate(new Uri(uri, UriKind.RelativeOrAbsolute));
       }
    }
 }

As shown in above code, i have created NavigationService class which implements INavigationServiceInteface.

To Navigate one page to another page we are using PhoneApplicationFrame and will navigate page to this frame.

If we have paremeters, we can pass using querystring append with Uri.

For IDictionary, we need to add System.Collections.Generic namespace into class.

Step 3 : Create Method in BaseViewModel that return NavigationContext.

   public class BaseViewModel : ViewModelBase
    {
        public T GetService() where T : class
        {
            if (typeof(T) == typeof(INavigationService))
            {
                return new NavigationService() as T;
            }
            return null;
        }
    }
  
This will return current INavigationService Interface object.

Step 4 : Calling Navigate Method from Page

Suppose, I have ProductViewModel and I want to navigate my page from ProductView to OrderView, I am executing command from ViewModel.


  private void BuyProductCommand_Execute()
  {
     Dictionary<string, string> parameters = new Dictionary<string, string>();
     INavigationService navigationService = this.GetService<INavigationService>();
     navigationService.Navigate("/PageNavigationMVVM_WP7;component/Views/OrderView.xaml", parameters);
  }

as described in above code, i am creating KeyValuepair object to pass parameter.

this.GetService method will get current NavigationService object.

 using this object we can navigate page by passing Uri information.

Step 5 :Create Command in View

First add two namespaces; one for Interactivity, one for GalaSoft.MvvmLight Command.

  xmlns:Interactivity="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
  xmlns:command="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.WP7"

Place Button control in Page and modify as below.

    <Button Content="Buy Product">
       <Interactivity:Interaction.Triggers>
          <Interactivity:EventTrigger EventName="Click">
             <command:EventToCommand Command="{Binding BuyProductCommand}" />
          </Interactivity:EventTrigger>
       </Interactivity:Interaction.Triggers>
    </Button>

System.windows.Interactivity namespace is used to add Behavior to attached Object, fire trigger on specific event and many more.


Conclusion

when you are using MVVM and going for page navigation this source is useful for you. and you can navigate page with same namespace or different namespace.

Click MVVMPageNavigationInWP7 To Download Souce

2 comments:

  1. Good article... only that you not explain how to get the value that you pass to the second page...

    ReplyDelete