×
Namespaces

Variants
Actions
(Difference between revisions)

Como usar Cimbalino Windows Phone Toolkit Location

From Nokia Developer Wiki
Jump to: navigation, search
saramgsilva (Talk | contribs)
(Saramgsilva -)
hamishwillee (Talk | contribs)
m (Hamishwillee - Tidy code snippets)
Line 1: Line 1:
 
[[Category:Windows Phone 7.5]][[Category:Windows Phone 8]][[Category:Lang-Portuguese]][[Category:How To]][[Category:MVVM Light Toolkit]][[Category:Cimbalino Windows Phone Toolkit]]
 
[[Category:Windows Phone 7.5]][[Category:Windows Phone 8]][[Category:Lang-Portuguese]][[Category:How To]][[Category:MVVM Light Toolkit]][[Category:Cimbalino Windows Phone Toolkit]]
 
{{Abstract|Este artigo mostra como usar o Cimbalino Windows Phone Toolkit Location – LocationService. }}  
 
{{Abstract|Este artigo mostra como usar o Cimbalino Windows Phone Toolkit Location – LocationService. }}  
 
 
 
{{ArticleMetaData <!-- v1.3 -->
 
{{ArticleMetaData <!-- v1.3 -->
 
|sourcecode= <!-- Link to example source code e.g. [[Media:The Code Example ZIP.zip]] -->
 
|sourcecode= <!-- Link to example source code e.g. [[Media:The Code Example ZIP.zip]] -->
Line 22: Line 20:
 
|author= [[User:saramgsilva]]<!-- Enter link [[User:username]] -->
 
|author= [[User:saramgsilva]]<!-- Enter link [[User:username]] -->
 
}}
 
}}
 
  
 
== Introdução ==
 
== Introdução ==
Line 49: Line 46:
  
 
<code csharp>
 
<code csharp>
/// <summary>
 
 
     /// This class contains static references to all the view models in the
 
     /// This class contains static references to all the view models in the
 
     /// application and provides an entry point for the bindings.
 
     /// application and provides an entry point for the bindings.
    /// </summary>
 
 
     public class ViewModelLocator
 
     public class ViewModelLocator
 
     {
 
     {
        /// <summary>
 
 
         /// Initializes a new instance of the ViewModelLocator class.
 
         /// Initializes a new instance of the ViewModelLocator class.
        /// </summary>
 
 
         public ViewModelLocator()
 
         public ViewModelLocator()
 
         {
 
         {
Line 68: Line 61:
 
         }
 
         }
 
   
 
   
        /// <summary>
 
 
         /// Gets the main view model.
 
         /// Gets the main view model.
        /// </summary>
 
        /// <value>
 
        /// The main view model.
 
        /// </value>
 
 
         public MainViewModel MainViewModel
 
         public MainViewModel MainViewModel
 
         {
 
         {
Line 103: Line 91:
 
     using GalaSoft.MvvmLight.Command;
 
     using GalaSoft.MvvmLight.Command;
 
     using GalaSoft.MvvmLight;
 
     using GalaSoft.MvvmLight;
    /// <summary>
+
 
 
     /// This class contains properties that the main View can data bind to.
 
     /// This class contains properties that the main View can data bind to.
    /// </summary>
 
 
     public class MainViewModel : ViewModelBase
 
     public class MainViewModel : ViewModelBase
 
     {
 
     {
        /// <summary>
 
 
         /// The location service
 
         /// The location service
        /// </summary>
 
 
         private readonly ILocationService _locationService;
 
         private readonly ILocationService _locationService;
 
   
 
   
 
         private bool _isLocationEnable;
 
         private bool _isLocationEnable;
 
   
 
   
        /// <summary>
 
 
         /// Define if is start enable
 
         /// Define if is start enable
        /// </summary>
 
 
         private bool _isStartEnable;
 
         private bool _isStartEnable;
 
   
 
   
        /// <summary>
 
 
         /// Define if is stop enable
 
         /// Define if is stop enable
        /// </summary>
 
 
         private bool _isStopEnable;
 
         private bool _isStopEnable;
 
   
 
   
        /// <summary>
 
 
         /// The latitude
 
         /// The latitude
        /// </summary>
 
 
         private double _latitude;
 
         private double _latitude;
 
   
 
   
        /// <summary>
+
         /// The longitude
         /// The logitude
+
        /// </summary>
+
 
         private double _longitude;
 
         private double _longitude;
 
   
 
   
        /// <summary>
 
 
         /// The status
 
         /// The status
        /// </summary>
 
 
         private LocationServiceStatus _status;
 
         private LocationServiceStatus _status;
        /// <summary>
+
 
 
         /// Initializes a new instance of the MainViewModel class.
 
         /// Initializes a new instance of the MainViewModel class.
        /// </summary>
 
 
         public MainViewModel(ILocationService locationService)
 
         public MainViewModel(ILocationService locationService)
 
         {
 
         {
Line 156: Line 130:
 
         }
 
         }
 
   
 
   
        /// <summary>
 
 
         /// Gets or sets a value indicating whether [is location enable].
 
         /// Gets or sets a value indicating whether [is location enable].
        /// </summary>
 
        /// <value>
 
        ///  <c>true</c> if [is location enable]; otherwise, <c>false</c>.
 
        /// </value>
 
 
         public bool IsLocationEnable
 
         public bool IsLocationEnable
 
         {
 
         {
Line 174: Line 143:
 
         }
 
         }
 
   
 
   
        /// <summary>
+
         /// Gets or sets a value indicating whether [is start enable] if [is start enable]; otherwise false
         /// Gets or sets a value indicating whether [is start enable].
+
        /// </summary>
+
        /// <value>
+
        ///  <c>true</c> if [is start enable]; otherwise, <c>false</c>.
+
        /// </value>
+
 
         public bool IsStartEnable
 
         public bool IsStartEnable
 
         {
 
         {
Line 192: Line 156:
 
         }
 
         }
 
   
 
   
        /// <summary>
+
 
 
         /// Gets or sets a value indicating whether [is stop enable].
 
         /// Gets or sets a value indicating whether [is stop enable].
        /// </summary>
 
        /// <value>
 
        ///  <c>true</c> if [is stop enable]; otherwise, <c>false</c>.
 
        /// </value>
 
 
         public bool IsStopEnable
 
         public bool IsStopEnable
 
         {
 
         {
Line 210: Line 170:
 
         }
 
         }
 
   
 
   
        /// <summary>
 
 
         /// Gets or sets the latitude.
 
         /// Gets or sets the latitude.
        /// </summary>
 
        /// <value>
 
        /// The latitude.
 
        /// </value>
 
 
         public double Latitude
 
         public double Latitude
 
         {
 
         {
Line 228: Line 183:
 
         }
 
         }
 
   
 
   
        /// <summary>
 
 
         /// Gets or sets the location command.
 
         /// Gets or sets the location command.
        /// </summary>
 
        /// <value>
 
        /// The get location command.
 
        /// </value>
 
 
         public ICommand LocationCommand { get; private set; }
 
         public ICommand LocationCommand { get; private set; }
 
   
 
   
        /// <summary>
 
 
         /// Gets or sets the longitude.
 
         /// Gets or sets the longitude.
        /// </summary>
 
        /// <value>
 
        /// The logitude.
 
        /// </value>
 
 
         public double Longitude
 
         public double Longitude
 
         {
 
         {
Line 254: Line 199:
 
         }
 
         }
 
   
 
   
        /// <summary>
+
 
 
         /// Gets or sets the start command.
 
         /// Gets or sets the start command.
        /// </summary>
 
        /// <value>
 
        /// The start command.
 
        /// </value>
 
 
         public ICommand StartCommand { get; private set; }
 
         public ICommand StartCommand { get; private set; }
 
   
 
   
        /// <summary>
 
 
         /// Gets or sets the status.
 
         /// Gets or sets the status.
        /// </summary>
 
        /// <value>
 
        /// The status.
 
        /// </value>
 
 
         public LocationServiceStatus Status
 
         public LocationServiceStatus Status
 
         {
 
         {
Line 279: Line 215:
 
             }
 
             }
 
         }
 
         }
        /// <summary>
+
 
 
         /// Gets or sets the stop command.
 
         /// Gets or sets the stop command.
        /// </summary>
 
        /// <value>
 
        /// The stop command.
 
        /// </value>
 
 
         public ICommand StopCommand { get; private set; }
 
         public ICommand StopCommand { get; private set; }
        /// <summary>
+
 
 
         /// Unregisters this instance from the Messenger class.
 
         /// Unregisters this instance from the Messenger class.
        /// <para>To cleanup additional resources, override this method, clean
 
        /// up and then call base.Cleanup().</para>
 
        /// </summary>
 
 
         public override void Cleanup()
 
         public override void Cleanup()
 
         {
 
         {
Line 298: Line 227:
 
         }
 
         }
 
   
 
   
        /// <summary>
 
 
         /// Gets the location.
 
         /// Gets the location.
        /// </summary>
 
 
         private async void GetLocation()
 
         private async void GetLocation()
 
         {
 
         {
Line 308: Line 235:
 
         }
 
         }
 
   
 
   
        /// <summary>
+
 
 
         /// Handles the PositionChanged event of the LocationService control.
 
         /// Handles the PositionChanged event of the LocationService control.
        /// </summary>
 
        /// <param name="sender">The source of the event.</param>
 
        /// <param name="e">The <see cref="LocationServicePositionChangedEventArgs"/> instance containing the event data.</param>
 
 
         private void LocationService_PositionChanged(object sender, LocationServicePositionChangedEventArgs e)
 
         private void LocationService_PositionChanged(object sender, LocationServicePositionChangedEventArgs e)
 
         {
 
         {
Line 322: Line 246:
 
         }
 
         }
 
   
 
   
        /// <summary>
 
 
         /// Handles the StatusChanged event of the _locationService control.
 
         /// Handles the StatusChanged event of the _locationService control.
        /// </summary>
 
        /// <param name="sender">The source of the event.</param>
 
        /// <param name="e">The <see cref="LocationServiceStatusChangedEventArgs"/> instance containing the event data.</param>
 
 
         private void LocationService_StatusChanged(object sender, LocationServiceStatusChangedEventArgs e)
 
         private void LocationService_StatusChanged(object sender, LocationServiceStatusChangedEventArgs e)
 
         {
 
         {
Line 343: Line 263:
 
         }
 
         }
 
   
 
   
        /// <summary>
 
 
         /// Stops the location service.
 
         /// Stops the location service.
        /// </summary>
 
 
         private void Stop()
 
         private void Stop()
 
         {
 
         {

Revision as of 01:18, 26 November 2013

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
Tested with
SDK: Windows Phone 8.0 SDK, Windows Phone 7.1.1. SDK
Devices(s): Lumia 800, Lumia 920
CompatibilityPlatform Security
Capabilities: ID_CAP_LOCATION
Article
Translated:
By saramgsilva
Last edited: hamishwillee (26 Nov 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 (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:

    /// This class contains static references to all the view models in the
/// application and provides an entry point for the bindings.
public class ViewModelLocator
{
/// Initializes a new instance of the ViewModelLocator class.
public ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
if (!SimpleIoc.Default.IsRegistered<ILocationService>())
{
SimpleIoc.Default.Register<ILocationService, LocationService>();
}
SimpleIoc.Default.Register<MainViewModel>();
}
 
/// Gets the main view model.
public MainViewModel MainViewModel
{
get
{
return ServiceLocator.Current.GetInstance<MainViewModel>();
}
}
 
public static void Cleanup()
{
// TODO Clear the ViewModels
var viewModelLocator = (ViewModelLocator)App.Current.Resources["Locator"];
viewModelLocator.MainViewModel.Cleanup();
}
}

Implementando a ViewModel

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

 using System.Windows;
using System.Windows.Input;
using System.Windows.Threading;
 
using Cimbalino.Phone.Toolkit.Services;
 
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight;
 
/// This class contains properties that the main View can data bind to.
public class MainViewModel : ViewModelBase
{
/// The location service
private readonly ILocationService _locationService;
 
private bool _isLocationEnable;
 
/// Define if is start enable
private bool _isStartEnable;
 
/// Define if is stop enable
private bool _isStopEnable;
 
/// The latitude
private double _latitude;
 
/// The longitude
private double _longitude;
 
/// The status
private LocationServiceStatus _status;
 
/// Initializes a new instance of the MainViewModel class.
public MainViewModel(ILocationService locationService)
{
IsStartEnable = true;
IsLocationEnable = true;
IsStopEnable = false;
_locationService = locationService;
_locationService.ReportInterval = 5;
_locationService.PositionChanged += LocationService_PositionChanged;
_locationService.StatusChanged += LocationService_StatusChanged;
StartCommand =new RelayCommand(Start);
StopCommand =new RelayCommand(Stop);
LocationCommand = new RelayCommand(GetLocation);
}
 
/// Gets or sets a value indicating whether [is location enable].
public bool IsLocationEnable
{
get
{
return this._isLocationEnable;
}
set
{
Set("IsLocationEnable", ref _isLocationEnable, value);
}
}
 
/// Gets or sets a value indicating whether [is start enable] if [is start enable]; otherwise false
public bool IsStartEnable
{
get
{
return this._isStartEnable;
}
set
{
Set("IsStartEnable", ref _isStartEnable, value);
}
}
 
 
/// Gets or sets a value indicating whether [is stop enable].
public bool IsStopEnable
{
get
{
return this._isStopEnable;
}
set
{
Set("IsStopEnable", ref _isStopEnable, value);
}
}
 
/// Gets or sets the latitude.
public double Latitude
{
get
{
return _latitude;
}
set
{
Set("Latitude", ref _latitude, value);
}
}
 
/// Gets or sets the location command.
public ICommand LocationCommand { get; private set; }
 
/// Gets or sets the longitude.
public double Longitude
{
get
{
return this._longitude;
}
set
{
Set("Longitude", ref _longitude, value);
}
}
 
 
/// Gets or sets the start command.
public ICommand StartCommand { get; private set; }
 
/// Gets or sets the status.
public LocationServiceStatus Status
{
get
{
return _status;
}
set
{
Set("Status", ref _status, value);
}
}
 
/// Gets or sets the stop command.
public ICommand StopCommand { get; private set; }
 
/// Unregisters this instance from the Messenger class.
public override void Cleanup()
{
base.Cleanup();
_locationService.PositionChanged -= LocationService_PositionChanged;
_locationService.StatusChanged -= LocationService_StatusChanged;
}
 
/// Gets the location.
private async void GetLocation()
{
var result = await _locationService.GetPositionAsync();
Longitude = result.Longitude;
Latitude = result.Latitude;
}
 
 
/// Handles the PositionChanged event of the LocationService control.
private void LocationService_PositionChanged(object sender, LocationServicePositionChangedEventArgs e)
{
Deployment.Current.Dispatcher.BeginInvoke(delegate
{
Latitude = e.Position.Latitude;
Longitude = e.Position.Longitude;
});
}
 
/// Handles the StatusChanged event of the _locationService control.
private void LocationService_StatusChanged(object sender, LocationServiceStatusChangedEventArgs e)
{
Deployment.Current.Dispatcher.BeginInvoke(delegate { Status = e.Status; });
}
 
/// <summary>
/// Starts the location service.
/// </summary>
private void Start()
{
IsStartEnable = false;
IsStopEnable = true;
IsLocationEnable = false;
_locationService.Start();
}
 
/// Stops the location service.
private void Stop()
{
IsLocationEnable = true;
IsStartEnable = true;
IsStopEnable = false;
_locationService.Stop();
}
}

Implementando a View

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

<phone:PhoneApplicationPage x:Class="CimbalinoSample.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
DataContext="{Binding MainViewModel,
Source={StaticResource Locator}}"

FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
Orientation="Portrait"
SupportedOrientations="Portrait"
shell:SystemTray.IsVisible="True"
mc:Ignorable="d">
 
<!-- LayoutRoot is the root grid where all page content is placed -->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
 
<!-- TitlePanel contains the name of the application and page title -->
<StackPanel x:Name="TitlePanel"
Grid.Row="0"
Margin="12,17,0,28">
<TextBlock Margin="12,0"
Style="{StaticResource PhoneTextTitle2Style}"
Text="Cimbalino Sample" />
<TextBlock Margin="9,-7,0,0"
Style="{StaticResource PhoneTextTitle1Style}"
Text="Location" />
</StackPanel>
 
<!-- ContentPanel - place additional content here -->
<Grid x:Name="ContentPanel"
Grid.Row="1"
Margin="12,0,12,0">
<TextBlock TextWrapping="Wrap">
Latitude:<Run Text="{Binding Latitude}" />
</TextBlock>
<TextBlock Margin="0,51,0,-51" TextWrapping="Wrap">
Logitude:<Run Text="{Binding Longitude}" />
</TextBlock>
<TextBlock Margin="0,102,0,-102" TextWrapping="Wrap">
Status:<Run Text="{Binding Status}" />
</TextBlock>
<Button Margin="0,298,0,214"
IsEnabled="{Binding IsStartEnable}"
Command="{Binding StartCommand}"
Content="Start" />
<Button Height="76"
IsEnabled="{Binding IsStopEnable}"
Margin="0,0,0,138"
VerticalAlignment="Bottom"
Command="{Binding StopCommand}"
Content="Stop" />
<Button Margin="0,219,0,293"
IsEnabled="{Binding IsLocationEnable}"
Command="{Binding LocationCommand}"
Content="Get location" />
</Grid>
</Grid>
</phone:PhoneApplicationPage>
72 page views in the last 30 days.
×