×
Namespaces

Variants
Actions
(Difference between revisions)

Como usar Cimbalino Windows Phone Toolkit Location

From Nokia Developer Wiki
Jump to: navigation, search
hamishwillee (Talk | contribs)
m (Hamishwillee - Tidy code snippets)
hamishwillee (Talk | contribs)
m (Hamishwillee - Bot update - Fix metadata)
Line 6: Line 6:
 
|devices= Lumia 800, Lumia 920<!-- Devices tested against - e.g. Nokia Lumia 928, Nokia Asha 501) -->
 
|devices= Lumia 800, Lumia 920<!-- Devices tested against - e.g. Nokia Lumia 928, Nokia Asha 501) -->
 
|sdk= Windows Phone 8.0 SDK, Windows Phone 7.1.1. SDK<!-- SDK(s) built and tested against (e.g. Windows Phone 8.0 SDK) -->
 
|sdk= Windows Phone 8.0 SDK, Windows Phone 7.1.1. SDK<!-- SDK(s) built and tested against (e.g. Windows Phone 8.0 SDK) -->
|dependencies= <!-- Any other/external dependencies e.g.: Google Maps Api v1.0 -->  
+
|dependencies= <!-- Any other/external dependencies e.g.: Google Maps Api v1.0 -->
|signing=<!-- Special Signing requirements -->
+
|signing= <!-- Special Signing requirements -->
 
|capabilities= ID_CAP_LOCATION<!-- Required capabilities for code (e.g. ID_CAP_LOCATION, ID_CAP_NETWORKING) -->
 
|capabilities= ID_CAP_LOCATION<!-- Required capabilities for code (e.g. ID_CAP_LOCATION, ID_CAP_NETWORKING) -->
|language= <!-- Language category code for non-English topics - e.g. Lang-Chinese -->
+
|language= Lang-Portuguese
 
|translated-by= [[User:saramgsilva]]<!-- [[User:XXXX]] -->
 
|translated-by= [[User:saramgsilva]]<!-- [[User:XXXX]] -->
|translated-from-title= How to use Cimbalino Windows Phone Toolkit Location<!-- Title only - not link -->  
+
|translated-from-title= How to use Cimbalino Windows Phone Toolkit Location<!-- Title only - not link -->
 
|translated-from-id= <!-- Id of translated revision -->
 
|translated-from-id= <!-- Id of translated revision -->
|review-by=<!-- After re-review: [[User:username]] -->
+
|review-by= <!-- After re-review: [[User:username]] -->
 
|review-timestamp= <!-- After re-review: YYYYMMDD -->
 
|review-timestamp= <!-- After re-review: YYYYMMDD -->
 
|update-by= <!-- After significant update: [[User:username]]-->
 
|update-by= <!-- After significant update: [[User:username]]-->
Line 347: Line 347:
 
</code>
 
</code>
  
<!-- Translation --> [[en:How to use Cimbalino Windows Phone Toolkit Location]]
+
<!-- Translation --> [[en:How to use Cimbalino Windows Phone Toolkit Location<!-- Title only - not link -->]]

Revision as of 07:41, 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

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 hamishwillee em 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>
74 page views in the last 30 days.
×