Introduction

The Cimbalino Windows Phone Toolkit delivers a set of useful and powerful MVVM-compatible tools and services to help developers build Silverlight applications for Windows Phone. The Toolkit is divided in projects that deliver various features, ranging from base MVVM services and helpers, through to code for background agents and for accessing media library, location services and so on. Cimbalino.Phone.Toolkit.Location is a MVVM compatible services for location access.

ILocationService represents an interface for a service capable of handling the device location capabilities. The implementation is: LocationService.

Building the example code

The source code for the code example is available here: Location Sample (Github).

To build the source code you will also need the MVVM Light Toolkit and the Cimbalino Windows Phone Toolkit. Their packages are available in the Nuget Package Manager.

Note: you must specify the following capabilities in the app manifest: ID_CAP_LOCATION.

Registering the service

Register the service in the ViewModelLocator constructor as shown below:

  1. /// This class contains static references to all the view models in the
  2. /// application and provides an entry point for the bindings.
  3. public class ViewModelLocator
  4. {
  5. /// Initializes a new instance of the ViewModelLocator class.
  6. public ViewModelLocator()
  7. {
  8. ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
  9. if (!SimpleIoc.Default.IsRegistered<ILocationService>())
  10. {
  11. SimpleIoc.Default.Register<ILocationService, LocationService>();
  12. }
  13. SimpleIoc.Default.Register<MainViewModel>();
  14. }
  15. /// Gets the main view model.
  16. public MainViewModel MainViewModel
  17. {
  18. get
  19. {
  20. return ServiceLocator.Current.GetInstance<MainViewModel>();
  21. }
  22. }
  23. public static void Cleanup()
  24. {
  25. // TODO Clear the ViewModels
  26. var viewModelLocator = (ViewModelLocator)App.Current.Resources["Locator"];
  27. viewModelLocator.MainViewModel.Cleanup();
  28. }
  29. }
Implementing the ViewModel

Then we should implement the MainViewModel class as in the following:
  1. using System.Windows;
  2. using System.Windows.Input;
  3. using System.Windows.Threading;
  4. using Cimbalino.Phone.Toolkit.Services;
  5. using GalaSoft.MvvmLight.Command;
  6. using GalaSoft.MvvmLight;
  7. /// This class contains properties that the main View can data bind to.
  8. public class MainViewModel : ViewModelBase
  9. {
  10. /// The location service
  11. private readonly ILocationService _locationService;
  12. private bool _isLocationEnable;
  13. /// Define if is start enable
  14. private bool _isStartEnable;
  15. /// Define if is stop enable
  16. private bool _isStopEnable;
  17. /// The latitude
  18. private double _latitude;
  19. /// The logitude
  20. private double _longitude;
  21. /// The status
  22. private LocationServiceStatus _status;
  23. /// Initializes a new instance of the MainViewModel class.
  24. public MainViewModel(ILocationService locationService)
  25. {
  26. IsStartEnable = true;
  27. IsLocationEnable = true;
  28. IsStopEnable = false;
  29. _locationService = locationService;
  30. _locationService.ReportInterval = 5;
  31. _locationService.PositionChanged += LocationService_PositionChanged;
  32. _locationService.StatusChanged += LocationService_StatusChanged;
  33. StartCommand =new RelayCommand(Start);
  34. StopCommand =new RelayCommand(Stop);
  35. LocationCommand = new RelayCommand(GetLocation);
  36. }
  37. /// Gets or sets a value indicating whether [is location enable].
  38. public bool IsLocationEnable
  39. {
  40. get
  41. {
  42. return this._isLocationEnable;
  43. }
  44. set
  45. {
  46. Set("IsLocationEnable", ref _isLocationEnable, value);
  47. }
  48. }
  49. /// Gets or sets a value indicating whether [is start enable].
  50. public bool IsStartEnable
  51. {
  52. get
  53. {
  54. return this._isStartEnable;
  55. }
  56. set
  57. {
  58. Set("IsStartEnable", ref _isStartEnable, value);
  59. }
  60. }
  61. /// Gets or sets a value indicating whether [is stop enable].
  62. public bool IsStopEnable
  63. {
  64. get
  65. {
  66. return this._isStopEnable;
  67. }
  68. set
  69. {
  70. Set("IsStopEnable", ref _isStopEnable, value);
  71. }
  72. }
  73. /// Gets or sets the latitude.
  74. public double Latitude
  75. {
  76. get
  77. {
  78. return _latitude;
  79. }
  80. set
  81. {
  82. Set("Latitude", ref _latitude, value);
  83. }
  84. }
  85. /// Gets or sets the location command.
  86. public ICommand LocationCommand { get; private set; }
  87. /// Gets or sets the longitude.
  88. public double Longitude
  89. {
  90. get
  91. {
  92. return this._longitude;
  93. }
  94. set
  95. {
  96. Set("Longitude", ref _longitude, value);
  97. }
  98. }
  99. /// Gets or sets the start command.
  100. public ICommand StartCommand { get; private set; }
  101. /// Gets or sets the status.
  102. public LocationServiceStatus Status
  103. {
  104. get
  105. {
  106. return _status;
  107. }
  108. set
  109. {
  110. Set("Status", ref _status, value);
  111. }
  112. }
  113. /// Gets or sets the stop command.
  114. public ICommand StopCommand { get; private set; }
  115. /// Unregisters this instance from the Messenger class.
  116. public override void Cleanup()
  117. {
  118. base.Cleanup();
  119. _locationService.PositionChanged -= LocationService_PositionChanged;
  120. _locationService.StatusChanged -= LocationService_StatusChanged;
  121. }
  122. /// Gets the location.
  123. private async void GetLocation()
  124. {
  125. var result = await _locationService.GetPositionAsync();
  126. Longitude = result.Longitude;
  127. Latitude = result.Latitude;
  128. }
  129. /// Handles the PositionChanged event of the LocationService control.
  130. private void LocationService_PositionChanged(object sender, LocationServicePositionChangedEventArgs e)
  131. {
  132. Deployment.Current.Dispatcher.BeginInvoke(delegate
  133. {
  134. Latitude = e.Position.Latitude;
  135. Longitude = e.Position.Longitude;
  136. });
  137. }
  138. /// Handles the StatusChanged event of the _locationService control.
  139. private void LocationService_StatusChanged(object sender, LocationServiceStatusChangedEventArgs e)
  140. {
  141. Deployment.Current.Dispatcher.BeginInvoke(delegate { Status = e.Status; });
  142. }
  143. /// Starts the location service.
  144. private void Start()
  145. {
  146. IsStartEnable = false;
  147. IsStopEnable = true;
  148. IsLocationEnable = false;
  149. _locationService.Start();
  150. }
  151. /// Stops the location service.
  152. private void Stop()
  153. {
  154. IsLocationEnable = true;
  155. IsStartEnable = true;
  156. IsStopEnable = false;
  157. _locationService.Stop();
  158. }
  159. }
Implementing the View

Add the binding in the main page is like:

  1. DataContext="{Binding MainViewModel, Source={StaticResource Locator}}"
  2. The MainPage.xaml can be the following:
  3. <phone:PhoneApplicationPage x:Class="CimbalinoSample.MainPage"
  4. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  5. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  6. xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  7. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  8. xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
  9. xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
  10. DataContext="{Binding MainViewModel,
  11. Source={StaticResource Locator}}"
  12. FontFamily="{StaticResource PhoneFontFamilyNormal}"
  13. FontSize="{StaticResource PhoneFontSizeNormal}"
  14. Foreground="{StaticResource PhoneForegroundBrush}"
  15. Orientation="Portrait"
  16. SupportedOrientations="Portrait"
  17. shell:SystemTray.IsVisible="True"
  18. mc:Ignorable="d">
  19. <!-- LayoutRoot is the root grid where all page content is placed -->
  20. <Grid x:Name="LayoutRoot" Background="Transparent">
  21. <Grid.RowDefinitions>
  22. <RowDefinition Height="Auto" />
  23. <RowDefinition Height="*" />
  24. </Grid.RowDefinitions>
  25. <!-- TitlePanel contains the name of the application and page title -->
  26. <StackPanel x:Name="TitlePanel"
  27. Grid.Row="0"
  28. Margin="12,17,0,28">
  29. <TextBlock Margin="12,0"
  30. Style="{StaticResource PhoneTextTitle2Style}"
  31. Text="Cimbalino Sample" />
  32. <TextBlock Margin="9,-7,0,0"
  33. Style="{StaticResource PhoneTextTitle1Style}"
  34. Text="Location" />
  35. </StackPanel>
  36. <!-- ContentPanel - place additional content here -->
  37. <Grid x:Name="ContentPanel"
  38. Grid.Row="1"
  39. Margin="12,0,12,0">
  40. <TextBlock TextWrapping="Wrap">
  41. Latitude:<Run Text="{Binding Latitude}" />
  42. </TextBlock>
  43. <TextBlock Margin="0,51,0,-51" TextWrapping="Wrap">
  44. Logitude:<Run Text="{Binding Longitude}" />
  45. </TextBlock>
  46. <TextBlock Margin="0,102,0,-102" TextWrapping="Wrap">
  47. Status:<Run Text="{Binding Status}" />
  48. </TextBlock>
  49. <Button Margin="0,298,0,214"
  50. IsEnabled="{Binding IsStartEnable}"
  51. Command="{Binding StartCommand}"
  52. Content="Start" />
  53. <Button Height="76"
  54. IsEnabled="{Binding IsStopEnable}"
  55. Margin="0,0,0,138"
  56. VerticalAlignment="Bottom"
  57. Command="{Binding StopCommand}"
  58. Content="Stop" />
  59. <Button Margin="0,219,0,293"
  60. IsEnabled="{Binding IsLocationEnable}"
  61. Command="{Binding LocationCommand}"
  62. Content="Get location" />
  63. </Grid>
  64. </Grid>
  65. </phone:PhoneApplicationPage>