• 20 heures
  • Moyenne

Ce cours est visible gratuitement en ligne.

Ce cours est en vidéo.

Vous pouvez obtenir un certificat de réussite à l'issue de ce cours.

J'ai tout compris !

Mis à jour le 29/06/2017

Approfondissez le MVVM

Connectez-vous ou inscrivez-vous gratuitement pour bénéficier de toutes les fonctionnalités de ce cours !

Téléchargez les fichiers d'audiodescription : Partie 3, Chapitre 5 et Partie 3, Chapitre 6

Vous trouverez sous la vidéo les codes source du cours.

Partie 1

Partie 2

Code Source

RelayCommand.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace System.Windows.Input
{
    public class RelayCommand<T> : ICommand
    {
        #region Fields

        private readonly Action<T> _execute = null;
        private readonly Predicate<T> _canExecute = null;

        #endregion

        #region Constructors

        /// <summary>
        /// Creates a new command that can always execute.
        /// </summary>
        /// <param name="execute">The execution logic.</param>
        public RelayCommand(Action<T> execute)
            : this(execute, null)
        {
        }

        /// <summary>
        /// Creates a new command with conditional execution.
        /// </summary>
        /// <param name="execute">The execution logic.</param>
        /// <param name="canExecute">The execution status logic.</param>
        public RelayCommand(Action<T> execute, Predicate<T> canExecute)
        {
            if (execute == null)
                throw new ArgumentNullException("execute");

            _execute = execute;
            _canExecute = canExecute;
        }

        #endregion

        #region ICommand Members

        public bool CanExecute(object parameter)
        {
            return _canExecute == null ? true : _canExecute((T)parameter);
        }

        public event EventHandler CanExecuteChanged
        {
            add
            {
                if (_canExecute != null)
                    CommandManager.RequerySuggested += value;
            }
            remove
            {
                if (_canExecute != null)
                    CommandManager.RequerySuggested -= value;
            }
        }

        public void Execute(object parameter)
        {
            _execute((T)parameter);
        }

        #endregion
    }
}

Client.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PremiereUtilisationDUnDatacontext
{
    public class Client : INotifyPropertyChanged
    {
        private string nom;

        private string prenom;

        private string sexe;

        private int age;

        public event PropertyChangedEventHandler PropertyChanged;

        public string Nom
        {
            get
            {
                return nom;
            }

            set
            {
                if (value != nom)
                { 
                    nom = value;
                    if (PropertyChanged != null)
                    {
                        PropertyChanged(this, new PropertyChangedEventArgs("Nom"));
                    }
                }
            }
        }

        public string Prenom
        {
            get
            {
                return prenom;
            }

            set
            {
                if (value != prenom)
                {
                    prenom = value;
                    if (PropertyChanged != null)
                    {
                        PropertyChanged(this, new PropertyChangedEventArgs("Prenom"));
                    }
                }
            }
        }

        public string Sexe
        {
            get
            {
                return sexe;
            }

            set
            {
                if (value != sexe)
                {
                    sexe = value;
                    if (PropertyChanged != null)
                    {
                        PropertyChanged(this, new PropertyChangedEventArgs("Sexe"));
                    }
                }
            }
        }

        public int Age
        {
            get
            {
                return age;
            }

            set
            {
                if (value != age)
                {
                    age = value;
                    if (PropertyChanged != null)
                    {
                        PropertyChanged(this, new PropertyChangedEventArgs("Age"));
                    }
                }
            }
        }
    }
}

FicheClientsViewModel.cs

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace PremiereUtilisationDUnDatacontext
{
    public class FicheClientsViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public void NotifyPropertyChanged([CallerMemberName] string str="")
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(str));
            }
        }

        private ObservableCollection<Client> fiches;

        public ObservableCollection<Client> Fiches
        {
            get
            {
                return fiches;
            }

            set
            {
                if (value != fiches)
                {
                    fiches = value;
                    NotifyPropertyChanged();
                }
            }
        }
        
        private Client ficheSelectionnee;

        public Client FicheSelectionnee
        {
            get
            {
                return ficheSelectionnee;
            }

            set
            {
                if (value != ficheSelectionnee)
                {
                    ficheSelectionnee = value;
                    NotifyPropertyChanged();
                }
            }
        }

        

        public FicheClientsViewModel()
        {
            Fiches = new ObservableCollection<Client>();
            
            FicheSelectionnee = new Client()
            {
                Nom = "Dupont",
                Prenom = "Pierre",
                Age = 32,
                Sexe = "M"
            };

            Fiches.Add(FicheSelectionnee);
        }

        private ICommand remiseAZeroDeLaFicheSelectionnee = new RelayCommand<Client>((client) =>
        {
            client.Age = 0;
            client.Nom = "";
            client.Prenom = "";
            client.Sexe = "";
        });

        public ICommand RemiseAZeroDeLaFicheSelectionnee
        {
            get
            {
                return remiseAZeroDeLaFicheSelectionnee;
            }
        }
        
        private ICommand ajoutDUneFicheClient;
        public ICommand AjoutDUneFicheClient
        {
            get
            {
                if (ajoutDUneFicheClient == null)
                {
                    ajoutDUneFicheClient = new RelayCommand<object>((obj) => Fiches.Add(new Client()));
                }
                return ajoutDUneFicheClient;
            }
        }

        private ICommand retraitDUneFicheClient;
        public ICommand RetraitDUneFicheClient
        {
            get
            {
                if (retraitDUneFicheClient == null)
                {
                    retraitDUneFicheClient = new RelayCommand<Client>((client) => Fiches.Remove(client));
                }
                return retraitDUneFicheClient;
            }
        }

        private ICommand editionDUneFicheClient;
        public ICommand EditionDUneFicheClient
        {
            get
            {
                if (editionDUneFicheClient == null)
                {
                    editionDUneFicheClient = new RelayCommand<Client>((client) => FicheSelectionnee = client);
                }
                return editionDUneFicheClient;
            }
        }
    }
}

MainWindow.xaml

<Window x:Class="PremiereUtilisationDUnDatacontext.MainWindow"
        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:local="clr-namespace:PremiereUtilisationDUnDatacontext"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Window.DataContext>
        <local:FicheClientsViewModel></local:FicheClientsViewModel>
    </Window.DataContext>
    <Grid>
        <Grid.Resources>
            <Style TargetType="Label">
                <Setter Property="HorizontalAlignment" Value="Center">
                </Setter>
                <Setter Property="VerticalAlignment" Value="Center">
                </Setter>
            </Style>
            <Style TargetType="TextBox">
                <Setter Property="HorizontalAlignment" Value="Stretch">
                </Setter>
                <Setter Property="VerticalAlignment" Value="Center">
                </Setter>
                <Setter Property="TextAlignment" Value="Center">
                </Setter>
            </Style>
        </Grid.Resources>
        <Grid.RowDefinitions>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
            <ColumnDefinition Width="5"/>
            <ColumnDefinition/>
            <ColumnDefinition/>
            <ColumnDefinition Width="5"/>
            <ColumnDefinition Width="2*"/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <Label Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2" HorizontalAlignment="Center" VerticalAlignment="Center">Interface d'édition</Label>
        <Label Grid.Row="0" Grid.Column="3" Grid.ColumnSpan="2" HorizontalAlignment="Center" VerticalAlignment="Center">Fiche Client</Label>
        <Label Grid.Row="1" Grid.Column="0">Nom :</Label>
        <Label Grid.Row="2" Grid.Column="0">Prénom :</Label>
        <Label Grid.Row="3" Grid.Column="0">Âge :</Label>
        <Label Grid.Row="4" Grid.Column="0">Sexe :</Label>
        <Rectangle Grid.Column="2" Grid.RowSpan="5" Fill="Black"></Rectangle>
        <TextBox Grid.Row="1" Grid.Column="1" Text="{Binding FicheSelectionnee.Nom, Mode=TwoWay}"></TextBox>
        <TextBox Grid.Row="2" Grid.Column="1" Text="{Binding FicheSelectionnee.Prenom, Mode=TwoWay}"></TextBox>
        <TextBox Grid.Row="3" Grid.Column="1" Text="{Binding FicheSelectionnee.Age, Mode=TwoWay}"></TextBox>
        <TextBox Grid.Row="4" Grid.Column="1" Text="{Binding FicheSelectionnee.Sexe, Mode=TwoWay}"></TextBox>
        <Label Grid.Row="1" Grid.Column="3">Nom :</Label>
        <Label Grid.Row="2" Grid.Column="3">Prénom :</Label>
        <Label Grid.Row="3" Grid.Column="3">Âge :</Label>
        <Label Grid.Row="4" Grid.Column="3">Sexe :</Label>
        <Label Grid.Row="1" Grid.Column="4" Content="{Binding FicheSelectionnee.Nom}"></Label>
        <Label Grid.Row="2" Grid.Column="4" Content="{Binding FicheSelectionnee.Prenom}"></Label>
        <Label Grid.Row="3" Grid.Column="4" Content="{Binding FicheSelectionnee.Age}"></Label>
        <Label Grid.Row="4" Grid.Column="4" Content="{Binding FicheSelectionnee.Sexe}"></Label>
        <Button Command="{Binding RemiseAZeroDeLaFicheSelectionnee}" CommandParameter="{Binding FicheSelectionnee}" Grid.ColumnSpan="5" Grid.Row="5">RAZ</Button>
        <Rectangle Grid.Column="5" Grid.RowSpan="6" Fill="Black"></Rectangle>
        <Label Grid.Column="6" Grid.Row="0" Grid.ColumnSpan="2">Fiches Clients</Label>
        <ListBox x:Name="listeDeFichesClients" Grid.Column="6" Grid.RowSpan="5" Grid.Row="1" ItemsSource="{Binding Fiches}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <Label Content="- "></Label>
                        <Label Content="{Binding Nom}"></Label>
                        <Label Content="{Binding Prenom}"></Label>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
        <Button Grid.Column="7" Grid.Row="1" Command="{Binding AjoutDUneFicheClient}">Ajouter</Button>
        <Button Grid.Column="7" Grid.Row="2" Command="{Binding RetraitDUneFicheClient}" CommandParameter="{Binding ElementName=listeDeFichesClients, Path=SelectedItem}">Retirer</Button>
        <Button Grid.Column="7" Grid.Row="3" Command="{Binding EditionDUneFicheClient}" CommandParameter="{Binding ElementName=listeDeFichesClients, Path=SelectedItem}">Editer</Button>
    </Grid>
</Window>

MainWindow.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace PremiereUtilisationDUnDatacontext
{
    /// <summary>
    /// Logique d'interaction pour MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }
}
Exemple de certificat de réussite
Exemple de certificat de réussite