Introducción a UWP (Universal Windows Platform) — Guía rápida

1. Xaml

1.1. Introducción a XAML

  • Información general de XAML
  • Se utiliza principalmente para crear elementos de interfaz de usuario (UI) visibles.
  • La sintaxis básica de Xaml se basa en XML.
  • Declarar un alias de espacio de nombres (namespace):
xmlns:controls="using:Common.Controls"
  • Usar clases declaradas en el namespace:
<controls:MyControl />
  • Recursos reutilizables (Resource),

    x:Key

<Style x:Key="TextBlock_Style" />
  • Nombre del elemento del control,

x:Name

Xaml:

<MyControl x:Name="myControl" />

C#:

private MyControl myControl;
  • Localización

    x:Uid

<TextBlock x:Uid="sampleText" />

1.2. Los controles más básicos (Control) – TextBlock, Button

<Page x:Class="MyPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <StackPanel>
        <TextBlock Text="Introducción a UWP" />
        <Button Content="Introducción a UWP" Click="Button_Click" />
    </StackPanel>
</Page>

2. MVVM

Detalles de MVVM

View <=> ViewModel <=> Model

  • View debe intentar contener solo el contenido de visualización de la UI; View se realiza principalmente usando el lenguaje Xaml;
  • ViewModel debe intentar no contener lógica de procesamiento de negocios, sino completar las acciones llamando a funciones en el Model;
  • Model debe intentar contener todos los datos y lógica de negocio, y tratar de no depender de View y ViewModel;

3. Interacción entre ViewModel y Model

3.1. ViewModel controla los datos de Model

ViewModel:

public class ViewModel
{
    private Model model;
    private ChangeA()
    {
        this.model.A = "A";
    }
}

Model:

public class Model
{
    public string A { get; set; }
    public string B { get; set; }
}

3.2. Model notifica a ViewModel – event

ViewModel:

public class ViewModel
{
private Model model;
    private ChangeA()
    {
        r.BEventArgs += this.Handler;
    }
    private void Handler(object sender, EventArgs e)
    {
        AnyActions();
    }
}

Model:

public delegate void BChangedHandler(object sender, EventArgs e);

public class Model
{
    public string A { get; set; }
    private string _B;
    public string B
    {
        get { return this._B; }
        set
        {
            this._B = value;
            if (BEventArgs != null)
            {
                BEventArgs(this, new EventArgs());
            }
        }
    }
    public event BChangedHandler BEventArgs;
}

4. Interacción entre View y ViewModel

4.1. Enlace de datos (Data Binding)

4.1.1. Enlace a ViewModel

View:

<TextBlock Text={Binding SampleText} />

ViewModel:

public string SampleText { get; set; }

4.1.2. Enlace a otros Control

View:

<TextBlock x:Name="TextBlock1" Text="SampleText" />
<Button Content="{Binding ElementName=TextBlock1, Path= Text}" />

4.1.3. Especificar DataContext

public ViewModelClass ViewModel { get; set; }

...
SpecifiedControl.DataContext = ViewModel;
...

5. (View y ViewModel) Implementar notificación de mensajes – INotifyPropertyChanged

Cuando SampleText cambia, se notificará al DependencyProperty enlazado a esa propiedad

public class MyControlViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public void Notify(string propName)
        {
            if (this.PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propName));
            }
        }

        private string _sampleText;
        public string SampleText
        {
            get
            {
                return _sampleText;
            }
            set
            {
                _sampleText = value;
                Notify(nameof(SampleText));
            }
        }
    }

O heredar de ViewModelBase

public class ViewModelBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public void Notify(string propName)
        {
            if (this.PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propName));
            }
        }
    }

6. (View y ViewModel) ListView enlazado a una fuente que implementa notificación de mensajes – ObservableCollection

ListView

Implementar el enlace a un ItemSource con notificación de mensajes en ListView

View:

<ListView ItemsSource="{Binding Items}">

ViewModel:

public ObservableCollection<Recording> Items { get; set; }
  • ObservableCollection solo genera notificaciones de mensajes cuando se agregan/eliminan Items o cuando se actualiza toda la lista;
  • Si se necesita notificar a la interfaz cuando cambia el contenido del Item Recording, Recording debe implementar INotifyPropertyChanged.

7. (View) Plantilla de Item de ListView (DataTemplate | UserControl)

7.1. DataTemplate

View:

<ListView ItemsSource="{Binding Items}">
    <ListView.ItemTemplate>
        <DataTemplate DataType="local:Recording">
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding A}" />
                <TextBlock Text="{Binding B}" />
            </StackPanel>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

ViewModel:

public ObservableCollection<RecordingViewModel> Items { get; set; }

public class RecordingViewModel : INotifyPropertyChanged
{
    ...
    Implementar INotifyPropertyChanged
    ...

    private Recording _recording;

    public string A
    {
        get
        {
            return this._recording.A;
        }
        set
        {
            this._recording.A = value;
            Notify(nameof(A));
        }
    }

    public string B { get; set; } = this._recording.B;

    public RecordingViewModel (Recording recording)
    {
        this._recording = recording;
    }
}

Model:

public class Recording
{
    public string A { get; set; }
    public string B { get; set; }
    public string C { get; set; }
    ... ...
}

Comparación:

Separar ViewModel/Model

7.2. UserControl

7.2.1. DependencyProperty

View:

<control:MyControl Text="La aplicación está buscando" IsSearching="{Binding ViewModel.IsSearching}" />

ViewModel:

public class MyControl
{
...
public static readonly DependencyProperty IsSearchingProperty =
    DependencyProperty.Register
    (
        "IsSearching", typeof(Boolean),
        typeof(MyControl), null
    );

public bool IsSearching
{
    get { return (bool)GetValue(IsSearchingProperty); }
    set { SetValue(IsSearchingProperty, value); }
}
...
}

8. (ViewModel y Model) Conversión de datos – IValueConverter

Se puede usar IValueConverter para realizar la conversión de datos entre ViewModel y Model.

public class ShowAllButtonVisibilityConverter:IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            if (value is IList)
            {
                int count = (value as IList).Count;
                if (count > 3)
                {
                    return Windows.UI.Xaml.Visibility.Visible;
                }
            }
            return Windows.UI.Xaml.Visibility.Collapsed;
        }

        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            if (value is IList)
            {
                int count = (value as IList).Count;
                if (count > 3)
                {
                    return Windows.UI.Xaml.Visibility.Visible;
                }
            }
            return Windows.UI.Xaml.Visibility.Collapsed;
        }

9. (View) Modificar el Style del Control

9.1. Personalizar Style dentro de Control

View:

<TextBlock Foreground="Red" Text="SampleText" />

9.2. Usar un Style unificado – ResourceDictionary

View:

<Window.Resources>
    <ResourceDictionary>
        <Style TargetType="TextBlock" x:Key="ImportantText">
            <Setter Property="Foreground" Value="Red" />
        </Style>
    </ResourceDictionary>
</Window.Resources>
...
<TextBlock Text="SampleText" Style={StaticResource ImportantText} />

9.3. Usar ThemeResource

View:

<Window.Resources>
    <ResourceDictionary>
        <ResourceDictionary.ThemeDictionaries>
            <ResourceDictionary x:Key="Light">
                <Style TargetType="TextBlock" x:Key="ImportantText">
                    <Setter Property="Foreground" Value="Red" />
                </Style>
            </ResourceDictionary>

            <ResourceDictionary x:Key="Dark">
                <Style TargetType="TextBlock" x:Key="ImportantText">
                    <Setter Property="Foreground" Value="Yellow" />
                </Style>
            </ResourceDictionary>

            <ResourceDictionary x:Key="HighContrast">
                <Style TargetType="TextBlock" x:Key="ImportantText">
                    <Setter Property="Foreground" Value="Black" />
                </Style>
            </ResourceDictionary>
        </ResourceDictionary.ThemeDictionaries>
    </ResourceDictionary>
</Window.Resources>
...
<TextBlock Text="SampleText" Style={ThemeResource ImportantText} />

10. Uso de Panel

10.1. Grid

Características:

  • De manera predeterminada, Height/Width es igual al elemento principal;

Sugerencias:

  • Definir el tamaño de diseño de los elementos secundarios en Grid;
  • Mostrar por proporción;

10.2. StackPanel

Características:

  • Puede exceder los límites del elemento principal;
  • Height o Width cambia con los elementos dentro del Panel;

Sugerencias:

  • Usar Padding y proporciones con flexibilidad;
  • Dar un valor al Width o Height del StackPanel en el elemento principal para evitar que el Control cruce los límites;

11. (View) IU Adaptable (Adaptive UI)

  • Usar VisualStateManager.VisualStateGroup
<VisualStateGroup>
    <VisualState x:Name="WideLayout">
        <VisualState.StateTriggers>
            <AdaptiveTrigger x:Name="WideLayoutTrigger" MinWindowWidth="1280" />
        </VisualState.StateTriggers>
        <VisualState.Setters>
            <Setter Target="SystemUpdateSideGrid.Width" Value="800" />
            <Setter Target="SystemUpdateSideGrid.Grid.Row" Value="0" />
        </VisualState.Setters>
    </VisualState>

    <VisualState x:Name="MidLayout">
        <VisualState.StateTriggers>
            <AdaptiveTrigger x:Name="MidLayoutTrigger" MinWindowWidth="700" />
        </VisualState.StateTriggers>
        <VisualState.Setters>
            <Setter Target="SystemUpdateSideGrid.Width" Value="400" />
            <Setter Target="SystemUpdateSideGrid.Grid.Row" Value="1" />
        </VisualState.Setters>
    </VisualState>
    ...
</VisualStateGroup>

12. Principios de diseño

  • No establecer explícitamente el tamaño de los elementos;
  • No utilizar coordenadas de pantalla para especificar la posición de los elementos;
  • Los elementos secundarios dentro del contenedor comparten el espacio disponible;
  • Contenedores de diseño anidables;

13. Localización

  • Usar x:Uid, identificador único del elemento
    <TextBlock x:Uid="S_TextBlock1" />
  • Usar archivo de recursos (Resources File)
    <data name="S_TextBlock1.Text" xml:space="preserve">
        <value>Texto de ejemplo</value>
    </data>

14. Convenciones de nomenclatura

Mayúscula inicial (PascalCase / big camel-case): firstName

Minúscula inicial (camelCase / little camel-case): FirstName

  • Class: PascalCase
  • Property: PascalCase
  • Field: camelCase con prefijo “_”
  • Control en Xaml: camelCase

15. Notas

  • Cambiar el nombre de las Property en ViewModel con precaución, porque los nombres de Binding en Xaml no seguirán la refactorización;