You are on page 1of 40

Separar lgica de interfaz de usuario y la aplicacin utilizando el

patrn de MVVM
Compartir funcionalidad utilizando bibliotecas de clases de portables
Compartir cdigo con Archivos Enlazados
Manejo de las diferencias de plataforma de Windows Phone y
Windows 8
Compartir utilizando componentes Windows Runtime
User Interface
App Logic
General Model-View-ViewModel (MVVM)
Model
View
ViewModel
Data Bindings
One way
One time
Two way
Commands
Interfaz de Usuario
Clases con solo
propiedades que
representan las fuentes de
los datos (archivos,
servicios, bases de datos)
Estructuras que
representan los contextos
de datos de las pantallas y
el que permiten el acceso
a la logica de negocio
Aplicaciones de escritorio, web forms
Caja de texto
Etiqueta
Form.cs (Code behind C#)
Form.designer.cs (C#)
Clase
Form
Usar code behind en clases parciales,
es el escenario tpico o ms sencillo
de un desarrollador .NET.
Aplicaciones XAML
Caja de texto
Etiqueta
MainPage.xaml
(Lenguaje declarativo XAML)
MainPage.xaml.cs (Code behind C#)
Clase
MainPage
Nuestra meta para
hacer cdigo portable
es usar code hind al
mnimo posible. En la
demo de hecho cero
code behind.
Usando XAML se pueden crear de forma declarativa los mismos
elementos grficos que se crearan en cdigo
<StackPanel>
<TextBox/>
<Button/>
</StackPanel>
StackPanel stackPanel = new StackPanel();
TextBox textBox = new TextBox();
stackPanel.Children.Add(textBox);
Button button = new Button();
stackPanel.Children.Add(button);
Ambos escenarios permiten acceder a los controles de la pantalla como
miembros de la clase que los contiene es decir
this.txtMensaje.Text = Hola;
Y crear event handlers para poner el cdigo relacionado a una interaccin del
usuario, por ejemplo el click de un botn
private void Button_Click(object sender, RoutedEventArgs e)
{ //Code }
Sin embargo como ya lo dijimos, est no es la mejor prctica para hacer
cdigo portable y reusable.
Nombre
Editar perfil
Apellido
12:38
recordar
*****
iniciar sesin
password
soreygarcia
usuario
Text={Binding alias}
Password={Binding password}
Command={Binding IniciarSesionCommand}
DataContext={Binding Path=Usuario, Source={StaticResource Locator}}
<StackPanel x:Name="ContentPanel" Margin="12,0,12,0" Grid.Row="1" >
<TextBlock TextWrapping="Wrap" Text="TextBlock"/>
<TextBox Height="72" TextWrapping="Wrap" Text="TextBox"/>
<TextBlock TextWrapping="Wrap" Text="TextBlock"/>
<TextBox Height="72" TextWrapping="Wrap" Text="TextBox"/>
<Button Content="Button"/>
</StackPanel>
<StackPanel x:Name="ContentPanel" Margin="12,0,12,0" Grid.Row="1">
<TextBlock TextWrapping="Wrap" Text="TextBlock"/>
<TextBox Height="72" TextWrapping="Wrap" Text="{Binding Nombre, Mode=TwoWay}"/>
<TextBlock TextWrapping="Wrap" Text="TextBlock"/>
<TextBox Height="72" TextWrapping="Wrap" Text="{Binding Apellido, Mode=TwoWay}"/>
<Button Content="Button"/>
</StackPanel>
<Grid x:Name="LayoutRoot" Background="Transparent"
d:DataContext="{Binding Path=Persona, Source={StaticResource SampleDataSource}}">
<Grid x:Name="ContentPanel">
<! Aqu van los dems elementos de nuestra vista -->
</Grid>
</Grid>
class Models
Player
property
+ Cl ues(): Li st<stri ng>
+ Id(): i nt
+ Name(): stri ng
+ Photo(): stri ng
Esta clase es suficiente
para serializar el archivo
que tenemos
class ViewModels
ClueViewModel
property
+ Name(): stri ng
+ Val ue(): stri ng
Bi ndabl eBase
MainViewModel
- j sonServi ce: IJsonServi ce
- navi gati onServi ce: INavi gati onServi ce
- phoneServi ce: IPhoneServi ce
- randomGen: Random
- LoadPl ayers(): voi d
+ Mai nVi ewModel (INavi gati onServi ce, IPhoneServi ce)
~ Suffl ePl ayers(): voi d
property
+ Pl ayers(): Observabl eCol l ecti on<Pl ayerVi ewModel >
+ Sel ectedPl ayer(): Pl ayerVi ewModel
Bi ndabl eBase
PlayerViewModel
- navi gati onServi ce: INavi gati onServi ce
- phoneServi ce: IPhoneServi ce
- wasDi scovered: bool
- Di scover(): voi d
- Guess(): voi d
+ Pl ayerVi ewModel (INavi gati onServi ce, IPhoneServi ce)
property
+ Answer(): stri ng
+ Cl ues(): Observabl eCol l ecti on<Cl ueVi ewModel >
+ Di scoverCommand(): ICommand
+ GuessCommand(): ICommand
+ Id(): i nt
+ Name(): stri ng
+ ParentVi ewModel (): Mai nVi ewModel
+ Photo(): stri ng
+ WasDi scovered(): bool
public class ItemViewModel : INotifyPropertyChanged
{
private string lineOne;
public string LineOne
{
get { return lineOne; }
set {
if (value != lineOne)
{
lineOne = value;
NotifyPropertyChanged("LineOne");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName)
{
if (null != PropertyChanged)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public class MainViewModel : BindableBase
{
private String nombre;
public String Nombre
{
get
{
return this.nombre;
}
set
{
nombre = value;
RaisePropertyChanged(Nombre);
}
}
private static HueClientViewModel hueClientVM = null;
public static HueClientViewModel HueClientVM
{
get{
if (hueClientVM == null)
hueClientVM = new HueClientViewModel();
return hueClientVM;
}
}
public HueClientView()
{
InitializeComponent();
this.DataContext = App.HueClientVM;
}
<Application x:Class="Hue_Demo_Phone.App ...
xmlns:vm="clr-namespace:Hue_Demo_Phone.ViewModels">
<Application.Resources>
<vm:HueClientViewModel x:Key="HueClientVM" />
</Application.Resources>
<phone:PhoneApplicationPage ...
"DataContext="{StaticResource HueClientVM}">
<phone:PhoneApplicationPage>
<!-- XAML -->
<phone:PhoneApplicationPage.DataContext>
<Binding Path="Main" Source="{StaticResource Locator}"/>
</phone:PhoneApplicationPage.DataContext>
<Grid x:Name="LayoutRoot" Background="Transparent" >
</Grid>
Events
Event
Handlers
Commanding
<StackPanel x:Name="ContentPanel" Margin="12,0,12,0" Grid.Row="1" >
<TextBlock TextWrapping="Wrap" Text="TextBlock"/>
<TextBox Height="72" TextWrapping="Wrap" Text="{Binding Nombre, Mode=TwoWay}"/>
<TextBlock TextWrapping="Wrap" Text="TextBlock"/>
<TextBox Height="72" TextWrapping="Wrap" Text="{Binding Apellido, Mode=TwoWay}"/>
<Button Content="Button" Command="{Binding GuardarPerfilCommand}"/>
</StackPanel>
<Button Content="Press this" Height="72" Margin="90,464,0,0" Name="button1" Width="300"
Command="{Binding HelloCommand}"/>
<ListBox Height="100" x:Name="listBox1" >
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<i:InvokeCommandAction Command="{Binding SelectionChanged}"
CommandParameter="{Binding ElementName=listBox1, Path=SelectedIndex}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</ListBox>
public ICommand GuardarPerfilCommand
{
get { return new RelayCommand(GuardarPerfil, null);}
}
private async void GuardarPerfil()
{
//Code
}
#endregion GuardarPerfil
class StickerBook
StickerBook.Logic
+ Common
+ Contracts
+ Model s
+ Servi ces
+ Vi ewModel s
StickerBook.WinPhone
+ App
+ Common
+ Converters
+ Pages
+ Properti es
+ Sampl eData
+ Servi ces
StickerBook.WinRT
+ App
+ Common
+ Converters
+ Pages
+ Properti es
+ Sampl eData
+ Servi ces

http://aka.ms/ShareCode

You might also like