×
Namespaces

Variants
Actions

Como usar Cimbalino Windows Phone Toolkit Location

From Nokia Developer Wiki
Jump to: navigation, search

Este artigo mostra como usar o Cimbalino Windows Phone Toolkit Location – LocationService.

SignpostIcon XAML 40.png
WP Metro Icon WP8.png
SignpostIcon WP7 70px.png
Article Metadata

Exemplo de código
Código fonte: Exemplo Location (github)

Testado com
SDK: Windows Phone 8.0 SDK, Windows Phone 7.1.1. SDK
Aparelho(s): Lumia 800, Lumia 920

Compatibilidade
Platform Security
Capabilities: ID_CAP_LOCATION

Artigo
Tradução:
Por saramgsilva
Última alteração feita por saramgsilva em 04 Dec 2013

Contents

Introdução

Cimbalino Windows Phone Toolkit é um conjunto de itens uteis e poderosos para ajudar na implementação de aplicações Windows Phone. Projeto base do toolkit contendo serviços para implementação do padrão de MVVM, conversores, classes auxiliares, métodos de extensões;

Cimbalino.Phone.Toolkit.UserInfo - Projeto do toolkit contendo serviços para implementação do padrão de MVVM com acesso à informação do utilizador.

  • ILocationService - Representa uma interface para um serviço capaz de lidar com as capacidades do dispositivo de localização.. A implementação é LocationService.

Note.pngNote: é preciso definir a capacidade ID_CAP_LOCATION no ficheiro manifest.

Contruindo o exemplo

O código fonte pode ser obtido em Exemplo Location (github).

Os pacotes estão disponíveis em Nuget Package Manager (para ambos os "targets") e podem ser instalados, para mais detalhes consultar: Como instalar os pacotes Cimbalino Windows Phone Toolkit. O exemplo deste artigo usa MVVM Light para ajudar na implementação do padrão MVVM, para mais detalhes consultar:

Registando os serviços

Devemos começar por registar cada serviço no ViewModelLocator, como podemos ver de seguida:

  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.  
  16.         /// Gets the main view model.
  17.         public MainViewModel MainViewModel
  18.         {
  19.             get
  20.             {
  21.                 return ServiceLocator.Current.GetInstance<MainViewModel>();
  22.             }
  23.         }
  24.  
  25.         public static void Cleanup()
  26.         {
  27.             // TODO Clear the ViewModels
  28.             var viewModelLocator = (ViewModelLocator)App.Current.Resources["Locator"];
  29.             viewModelLocator.MainViewModel.Cleanup();
  30.         }
  31.     }

Implementando a ViewModel

Em seguinda devemos implementar o MainViewModel, como podemos ver de seguida:

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

Implementando a View

A MainPage.xaml será algo do género:

  1. <phone:PhoneApplicationPage x:Class="CimbalinoSample.MainPage"
  2.                             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3.                             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4.                             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  5.                             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  6.                             xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
  7.                             xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
  8.                             DataContext="{Binding MainViewModel,
  9.                                                   Source={StaticResource Locator}}"
  10.                             FontFamily="{StaticResource PhoneFontFamilyNormal}"
  11.                             FontSize="{StaticResource PhoneFontSizeNormal}"
  12.                             Foreground="{StaticResource PhoneForegroundBrush}"
  13.                             Orientation="Portrait"
  14.                             SupportedOrientations="Portrait"
  15.                             shell:SystemTray.IsVisible="True"
  16.                             mc:Ignorable="d">
  17.  
  18.     <!--  LayoutRoot is the root grid where all page content is placed  -->
  19.     <Grid x:Name="LayoutRoot" Background="Transparent">
  20.         <Grid.RowDefinitions>
  21.             <RowDefinition Height="Auto" />
  22.             <RowDefinition Height="*" />
  23.         </Grid.RowDefinitions>
  24.  
  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.  
  37.         <!--  ContentPanel - place additional content here  -->
  38.         <Grid x:Name="ContentPanel"
  39.               Grid.Row="1"
  40.               Margin="12,0,12,0">
  41.             <TextBlock TextWrapping="Wrap">
  42.                 Latitude:<Run Text="{Binding Latitude}" />
  43.             </TextBlock>
  44.             <TextBlock Margin="0,51,0,-51" TextWrapping="Wrap">
  45.                 Logitude:<Run Text="{Binding Longitude}" />
  46.             </TextBlock>
  47.             <TextBlock Margin="0,102,0,-102" TextWrapping="Wrap">
  48.                 Status:<Run Text="{Binding Status}" />
  49.             </TextBlock>
  50.             <Button Margin="0,298,0,214"
  51.                     IsEnabled="{Binding IsStartEnable}"
  52.                     Command="{Binding StartCommand}"
  53.                     Content="Start" />
  54.             <Button Height="76"
  55.                     IsEnabled="{Binding IsStopEnable}"
  56.                     Margin="0,0,0,138"
  57.                     VerticalAlignment="Bottom"
  58.                     Command="{Binding StopCommand}"
  59.                     Content="Stop" />
  60.             <Button Margin="0,219,0,293"
  61.                     IsEnabled="{Binding IsLocationEnable}"
  62.                     Command="{Binding LocationCommand}"
  63.                     Content="Get location" />
  64.         </Grid>
  65.     </Grid>
  66. </phone:PhoneApplicationPage>
This page was last modified on 4 December 2013, at 16:00.
56 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.

 

Thank you!

We appreciate your feedback.

×