Namespaces

Variants
Actions

Please note that as of October 24, 2014, the Nokia Developer Wiki will no longer be accepting user contributions, including new entries, edits and comments, as we begin transitioning to our new home, in the Windows Phone Development Wiki. We plan to move over the majority of the existing entries over the next few weeks. Thanks for all your past and future contributions.

Como usar MVVM Light Toolkit para Windows Phone

From Wiki
Jump to: navigation, search

Este artigo tem como objetivo mostrar como usar MVVM Light Toolkit.

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

Testado com
SDK: Windows Phone 8.0 SDK
Aparelho(s): Nokia Lumia 920

Compatibilidade
Dependencies: MVVM Light

Artigo
Tradução:
Por saramgsilva
Última alteração feita por hamishwillee em 18 Nov 2013

Contents

Introdução

Model-View-ViewModel (MVVM) é o padrão de desenvolvimento recomendado para aplicações Windows Phones.

The elements of the MVVM pattern: Os elementos do padão MVVM são:

  • Views - representa as páginas (está relacionado com a UI).
  • ViewModel - representa as classes que serão usadas para conectar a interface com o modelo de dados.
  • Model - representa as classes que definem as entidades e a lógica de negócio.
Diagrama com um sumário sobre o padrão View ViewModel MVVM.

Existe diversos toolkits para ajudar na implementação do padrão Model-View-ViewModel MVVM, MVVM Light Toolkit é um deles!

Para instalar os pacotes consulte o seguinte artigo:Como instalar os pacotes de MVVM Light Toolkit para Windows Phone

Como usar

Depois de instalar os pacotes, podemos encontrar no App.xaml

   <vm:ViewModelLocator x:Key="Locator" d:IsDataSource="True" xmlns:vm="clr-namespace:MVVMLightSample.ViewModel" />

Que representa a instância para o ViewModelLocator. Para ajudar a conetar a página com a view model usamos o ViewModelLocator para gerir todos os view models e as suas dependências. Esta classe é representado no ficheiro ViewModelLocator.cs.

Cujo código é o seguinte:

    /// <summary>
/// This class contains static references to all the view models in the
/// application and provides an entry point for the bindings.
/// </summary>
public class ViewModelLocator
{
/// <summary>
/// Initializes a new instance of the ViewModelLocator class.
/// </summary>
public ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
 
////if (ViewModelBase.IsInDesignModeStatic)
////{
//// // Create design time view services and models
//// SimpleIoc.Default.Register<IDataService, DesignDataService>();
////}
////else
////{
//// // Create run time view services and models
//// SimpleIoc.Default.Register<IDataService, DataService>();
////}
 
SimpleIoc.Default.Register<MainViewModel>();
}
 
/// <summary>
/// Gets the main view model.
/// </summary>
/// <value>
/// The main view model.
/// </value>
public MainViewModel MainViewModel
{
get
{
return ServiceLocator.Current.GetInstance<MainViewModel>();
}
}
 
/// <summary>
/// Cleanups this instance.
/// </summary>
public static void Cleanup()
{
// TODO Clear the ViewModels
var viewModelLocator = (ViewModelLocator)Application.Current.Resources["Locator"];
viewModelLocator.MainViewModel.Cleanup();
 
Messenger.Reset();
}
}

Para conetar a view model com a página efuamos um binding da seguinte forma

  DataContext="{Binding MainViewModel,
Source={StaticResource Locator}}"

no ficheiro xaml da página principal.

O ficheiro MainViewModel.cs contém a classe MainViewModel que representa a view model para a página principal e esta classe herda da classe ViewModelBase, que representa a classe base para todas as classes que representam view models no padrão MVVM. Para este exemplo, the MainViewModel irá conter uma propriedade Person que irá lançar notificações quando o objecto Person for modificado.

Note.pngNote: Pelo facto de estar a usar o método Set as notificações só serão lançadas quando o novo valor do objecto for diferente do valor anterior.

A classe MainViewModel irá ser:

   public class MainViewModel : ViewModelBase
{
/// <summary>
/// The person
/// </summary>
private Person _person;
 
/// <summary>
/// Initializes a new instance of the MainViewModel class.
/// </summary>
public MainViewModel()
{
if (IsInDesignMode)
{
// Code runs in Blend --> create design time data.
_person = new Person { Name = "Sara", Age = 30 };
}
else
{
// Code runs "for real"
_person = new Person { Name = "Mary", Age = 35 };
}
 
PropertyChanged += MainViewModel_PropertyChanged;
ShowMessageCommand = new RelayCommand(ShowMessage);
}
 
/// <summary>
/// Gets or sets the person.
/// </summary>
/// <value>
/// The person.
/// </value>
public Person Person
{
get
{
return _person;
}
set
{
Set("Person", ref _person, value);
}
}
 
/// <summary>
/// Gets the show message command.
/// </summary>
/// <value>
/// The show message command.
/// </value>
public ICommand ShowMessageCommand { get; private set; }
 
/// <summary>
/// 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()
{
base.Cleanup();
PropertyChanged -= MainViewModel_PropertyChanged;
}
 
/// <summary>
/// Handles the PropertyChanged event of the MainViewModel control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.ComponentModel.PropertyChangedEventArgs"/> instance containing the event data.</param>
private void MainViewModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (e.PropertyName == "Person")
{
//Do someting if necessary
}
}
 
/// <summary>
/// Shows the message.
/// </summary>
private void ShowMessage()
{
Messenger.Default.Send("This is a message.");
}
}


Note.pngNote: O método Cleanup é útil para cancelar o registro de instância do modelo da classe Messenger e para limpeza de recursos adicionais, substituir este método, limpar e, em seguida, chamar base.Cleanup ().


A classe Person será representada por:

   public class Person : ObservableObject
{
public string _name;
public int _age;
 
public string Name
{
get
{
return _name;
}
set
{
Set("Name",ref _name, value);
}
}
 
public int Age
{
get
{
return _age;
}
set
{
Set("Age",ref _age, value);
}
}
 
}

Person é uma classe que herda de ObservableObject que representa uma classe base para objetos de que as propriedades devem ser observáveis ​​e ele herda de INotifyPropertyChanged e de INotifyPropertyChanging.

E na MainPage.xaml.cs vamos ter:

 public partial class MainPage 
{
/// <summary>
/// Initializes a new instance of the <see cref="MainPage"/> class.
/// </summary>
public MainPage()
{
InitializeComponent();
 
Messenger.Default.Register<string>(this, ShowMessage);
}
 
/// <summary>
/// Shows the message.
/// </summary>
/// <param name="message">The message.</param>
private void ShowMessage(string message)
{
MessageBox.Show(message);
}
}

Note.pngNote: A classe Messenger que permite a troca de mensagem e é possivel enviar qualquer tipo de objectos. Isto é útil para comunicar entre view models quando a página contém mais do que um view model.

E na MainPage.xaml vamos ter por exemplo:

<phone:PhoneApplicationPage x:Class="MVVMLightSample.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 PhoneTextNormalStyle}"
Text="MY APPLICATION" />
<TextBlock Margin="9,-7,0,0"
Style="{StaticResource PhoneTextTitle1Style}"
Text="Person" />
</StackPanel>
 
<!-- ContentPanel - place additional content here -->
<Grid x:Name="ContentPanel"
Grid.Row="1"
Margin="12,0,12,0">
<TextBlock HorizontalAlignment="Left"
VerticalAlignment="Top"
Text="Name"
TextWrapping="Wrap" />
<TextBox Height="70"
Margin="-10,32,10,505"
Text="{Binding Person.Name}"
TextWrapping="Wrap" />
<TextBlock Margin="10,107,0,0"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Text="Age"
TextWrapping="Wrap" />
<TextBox Height="70"
Margin="-10,139,10,398"
Text="{Binding Person.Age}"
TextWrapping="Wrap" />
 
<Button Height="115"
Margin="0,0,0,256"
VerticalAlignment="Bottom"
Command="{Binding ShowMessageCommand}"
Content="Show message!" />
</Grid>
 
<!--
Uncomment to see an alignment grid to help ensure your controls are
aligned on common boundaries. The image has a top margin of -32px to
account for the System Tray. Set this to 0 (or remove the margin altogether)
if the System Tray is hidden.
 
Before shipping remove this XAML and the image itself.
-->
<!-- <Image Source="/Assets/AlignmentGrid.png" VerticalAlignment="Top" Height="800" Width="480" Margin="0,-32,0,0" Grid.Row="0" Grid.RowSpan="2" IsHitTestVisible="False" /> -->
</Grid>
 
</phone:PhoneApplicationPage>

Ecrãs finais

Modo de desenho
Aplicação a correr

Código Fonte

O código fonte pode ser encontrado aqui.

Exemplos relacionados

Referências

(*) Disponível apenas em inglês.

This page was last modified on 18 November 2013, at 01:27.
248 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.

×