IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Développement Windows Discussion :

Wpf Datagrid Crud MVVM


Sujet :

Développement Windows

  1. #1
    Membre à l'essai
    Homme Profil pro
    Étudiant
    Inscrit en
    Novembre 2014
    Messages
    21
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 35
    Localisation : Belgique

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Novembre 2014
    Messages : 21
    Points : 20
    Points
    20
    Par défaut Wpf Datagrid Crud MVVM
    Bonsoir tout le monde,

    je cale complètement sur ce problème, j'ai une datagrid qui affiche correctement mes produits, qui les modifie, qui les supprime jusque la ok. Par contre j'ai un soucis concernant l'ajout. En effet je fais apparaître dans mes champs textes les string des cellules associées dans mes textbox et pour ce faire j'utilise en binding dans mes textbox le selected item. Du coup ca modifie et ca ajoute en meme temps. Avec le code ce sera plus clair :
    L'essentiel du Xaml de mon userControl
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    <TextBox x:Name="tbNom" Height="23" Text="{Binding SelectedProduit.Nom, Mode=TwoWay}" VerticalAlignment="Top" Margin="77,34,191,0" Grid.ColumnSpan="2" IsEnabled="True"/>
            <TextBox x:Name="tbLib" Grid.ColumnSpan="2" HorizontalAlignment="Left" Height="23" Margin="77,22,0,0" Text="{Binding  SelectedProduit.Libelle, Mode=TwoWay}" VerticalAlignment="Top" Width="120" Grid.Row="1"/>
            <TextBox x:Name="tbPoint" Grid.ColumnSpan="2" HorizontalAlignment="Left" Height="23" Margin="77,78,0,0" Text="{Binding SelectedProduit.PointFidelite, Mode=TwoWay}" VerticalAlignment="Top" Width="120" Grid.Row="1"/>
            <TextBox x:Name="tbTarif" Grid.ColumnSpan="2" Grid.Column="2" HorizontalAlignment="Left" Height="23" Margin="96,31,0,0" Text="{Binding SelectedProduit.Tarif, Mode=TwoWay}" VerticalAlignment="Top" Width="120"/>
            <CheckBox x:Name="tbSupprime" Grid.Column="2" HorizontalAlignment="Left" Margin="96,36,0,0" Grid.Row="1" VerticalAlignment="Top" Height="15" Width="20" IsChecked="{Binding SelectedProduit.ProduitSupprime, Mode=TwoWay}"/>
     
            <DataGrid x:Name="dataGridProduit" IsSynchronizedWithCurrentItem="True" SelectionMode="Single"
                      CanUserAddRows="False" Height="auto" Margin="19,129,19,13" Grid.Row="1" Width="auto" Grid.ColumnSpan="4" IsReadOnly="True" AutoGenerateColumns="false"
                      ItemsSource="{Binding MesProduits}" 
                      SelectedItem="{Binding SelectedProduit, Mode=TwoWay}">
                <DataGrid.Columns>
                    <DataGridTextColumn x:Name="Nom" Header="Nom" Binding="{Binding Nom, Mode=TwoWay}" Width="*"/>
                    <DataGridTextColumn x:Name="Libelle" Header="Libelle" Binding="{Binding Libelle, Mode=TwoWay}" Width="*"/>
                    <DataGridTextColumn x:Name="PointFidelite" Header="Point de Fidelite" Binding="{Binding PointFidelite, Mode=TwoWay}" Width="100"/>
                    <DataGridTextColumn x:Name="Tarif" Header="Prix unitaire" Binding="{Binding Tarif, Mode=TwoWay}" Width="*"/>
                    <DataGridTextColumn x:Name="ProduitSupprimé" Header="Produit Supprimé" Binding="{Binding ProduitSupprime, Mode=TwoWay}" Width="*"/>
                </DataGrid.Columns>
            </DataGrid>
     
            <Button x:Name="buttonAdd" Content="ajouter" Style="{DynamicResource ButtonStyleMainWindow}" Grid.Column="1" Command="{Binding AddCommand}" CommandParameter="{Binding SelectedProduit}" Height="20"/>
            <Button x:Name="buttonRemove" Content="supprimer" Style="{DynamicResource ButtonStyleMainWindow}" Grid.Column="2" Command="{Binding RemoveCommand}" CommandParameter="{Binding SelectedProduit}" Height="20"/>
            <Button x:Name="buttonUpdate" Content="modifier" Style="{DynamicResource ButtonStyleMainWindow}" Grid.Column="3" Command="{Binding EditCommand}" CommandParameter="{Binding SelectedProduit}" Height="20"/>
            <Button x:Name="buttonCancel" Content="annuler" Style="{DynamicResource ButtonStyleMainWindow}" Height="20" Command="{Binding CancelCommand}"/>
    le viewmodel
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
     private ObservableCollection<Produit> _mesProduits;
            private int _selectedIndex;
            private Produit _selectedProduit;
            private ICommand _editCommand;
            private ICommand _addCommand;
            private ICommand _removeCommand;
            private ICommand _cancelCommand;
            private string _nom;
            public ProductVM ProductVMTest { get; set; }
     
            public string Nom
            {
                get => _nom;
                set {
                    if(_nom != value)
                    {
                        _nom = value;
                        RaisePropertyChanged("Nom");
                    }
                }
            }
     
     
            public int SelectedIndex
            {
                get => _selectedIndex;
                set
                {
                    if (_selectedIndex != value)
                    {
                        _selectedIndex = value;
                        RaisePropertyChanged("SelectedIndex");
     
                    }
     
                }
            }
     
     
            public Produit SelectedProduit
            { 
                get => _selectedProduit;
                set
                {
                    if (_selectedProduit != value)
                    {
                        _selectedProduit = value;
                        RaisePropertyChanged("SelectedProduit");
                    }
                }
            }
     
     
            public ObservableCollection<Produit> MesProduits
            {
                get { return _mesProduits; }
                set
                {
                    if (_mesProduits != value)
                    {
                        _mesProduits = value;
                        RaisePropertyChanged("Articles");
                    }
                }
            }
     
            public ICommand EditCommand
            {
                get
                {
                    if (this._editCommand == null)
                    {
                        this._editCommand = new RelayCommand(UpdateProduit);
                    }
                    return _editCommand;
                }
            }
     
     
     
            public ICommand AddCommand
            {
                get
                {
                    if (this._addCommand == null)
                    {
                        this._addCommand = new RelayCommand(AddProduit);
                    }
                    return _addCommand;
                }
            }
     
            public ICommand RemoveCommand
            {
                get
                {
                    if (this._removeCommand == null)
                    {
                        this._removeCommand = new RelayCommand(RemoveProduit);
                    }
                    return _removeCommand;
                }
            }
     
            public ICommand CancelCommand
            {
                get
                {
                    if (this._cancelCommand == null)
                    {
                        this._cancelCommand = new RelayCommand(Cancel);
                    }
                    return _cancelCommand;
                }
            }
     
            public void Cancel(object parameter)
            {
                SelectedProduit = null;
            }
     
     
            public void UpdateProduit(object parameter)
            {
                var currentProduit = SelectedProduit;
                if (currentProduit != null)
                {
                    ProductBusiness.UpdateProduit(currentProduit);
                }
                MesProduits[SelectedIndex] = currentProduit;
            }
     
     
            public void AddProduit(object parameter)
            {
                var monProduit = parameter as Produit;
                ProductBusiness.AddProduit(monProduit);
                MesProduits.Add(new Produit() { Nom = monProduit.Nom, Libelle = monProduit.Libelle, Tarif = monProduit.Tarif, PointFidelite = monProduit.PointFidelite, ProduitSupprime = monProduit.ProduitSupprime });
            }
            public bool CanBeAdd(object parameter)
            {
                return true;
            }
            public void RemoveProduit(object parameter)
            {
                var selectedProduit = SelectedProduit;
                if (selectedProduit != null)
                {
                    ProductBusiness.RemoveProduit(SelectedIndex);
                }
                MesProduits.Remove(selectedProduit);
            }
     
            public ObservableCollection<Produit> LoadArticle()
            {
            MesProduits = ProductBusiness.ReadProduit();
            return MesProduits;
            }
     
            public ProductViewModel()
            {
                LoadArticle();
            }
    Si vous avez également des conseils sur le fait de rendre le code plus propre, j'en serai ravis.

    Merci beaucoup d'avance,
    Miniboom

  2. #2
    Membre habitué
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Novembre 2010
    Messages
    185
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haut Rhin (Alsace)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : Conseil

    Informations forums :
    Inscription : Novembre 2010
    Messages : 185
    Points : 167
    Points
    167
    Par défaut
    Salut,
    Sous la pression de WaterTwelve21, je me lance sans être certain d'avoir la bonne réponse ni même la réponse tout court... Je pense plutôt à la cause :
    Tu lies (binding) tes TextBox sur le SelectedItem donc quand tu changes quelque chose dedans c'est lié donc ça le change aussi dans ta liste (à la limite ton UpdateProduit ne sert à rien).

    Peut-être qu'il te faudrait mettre en Mode="OneWay" ce lien...

  3. #3
    Membre à l'essai
    Homme Profil pro
    Étudiant
    Inscrit en
    Novembre 2014
    Messages
    21
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 35
    Localisation : Belgique

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Novembre 2014
    Messages : 21
    Points : 20
    Points
    20
    Par défaut
    Non c'est pas ça, j'ai tenté ca déjà ^^ mais merci de ta contribution

  4. #4
    Membre habitué
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Novembre 2010
    Messages
    185
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haut Rhin (Alsace)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : Conseil

    Informations forums :
    Inscription : Novembre 2010
    Messages : 185
    Points : 167
    Points
    167
    Par défaut

  5. #5
    Membre chevronné
    Homme Profil pro
    edi
    Inscrit en
    Juin 2007
    Messages
    896
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Gironde (Aquitaine)

    Informations professionnelles :
    Activité : edi

    Informations forums :
    Inscription : Juin 2007
    Messages : 896
    Points : 1 912
    Points
    1 912
    Par défaut
    Ce comportement me parait tout à fait normal puisque tu as bindé en TwoWay tes TextBox sur le SelectedProduit. D'ailleurs, sur l'ajout, la modification d'un n'est fait qu'en mémoire et pas en en base. Il te faut rajouter une propriété TransferProduit de type Produit ou ProduitModel, et c'est sur cette propriété que tu binderas les TextBox (ou bien différentes propriétés Libelle, PointFidelite... mais ce sera probablement plus rapide avec une classe dédiée). Ce produit ne sert qu'à faire le passe-plat entre la vue et le modèle de vue et n'est lui-même jamais ajouté à la collection, il n'a d'importance que pour ses données. Ensuite tu te bindes sur ton propre événement de changement de SelectedProduit (je suppose que tu as implémenté INotifyPropertyChanged ou que tu utilises la classe de base ViewModelBase de MVVM Light) pour mettre à jour ce produit de transfert à chaque fois qu'un produit est sélectionné dans la DataGrid. Note que tu n'as pas besoin d'utiliser des CommandParameter avec tes boutons, puisque tous les paramètres utiles (TransferProduit, SelectedProduit, SelectedIndex) sont présents dans ta classe.

    Un autre détail c'est que les méthodes des classes de service (ProductBusiness.CreateProduct) pourraient dans certains cas renvoyer un objet (notamment justement l'ajout). Tu peux aussi te faire une ou deux méthodes utilitaires pour copier les données d'un objet sur un autre, par exemple avec des méthodes d'extension. Il reste ensuite à procéder aux ajustements sur les méthodes d'ajout, modification, etc... mais tu devrais t'en sortir maintenant.

    Bon courage

Discussions similaires

  1. WPF datagrid Dataset :probléme CRUD sur 2tables de BD
    Par casa_sniper dans le forum Windows Presentation Foundation
    Réponses: 0
    Dernier message: 14/12/2011, 16h12
  2. Ajouts en Masse [WPF] datagrid ou [Windows Form] Datagridview
    Par lerieure dans le forum Développement Windows
    Réponses: 0
    Dernier message: 05/12/2010, 13h58
  3. WPF - DataGrid du WPFToolKit : Accéder aux cellules pendant le chargement de la page
    Par YHDVP dans le forum Windows Presentation Foundation
    Réponses: 6
    Dernier message: 18/11/2009, 14h00
  4. C# WPF datagrid
    Par akkai dans le forum Windows Presentation Foundation
    Réponses: 2
    Dernier message: 08/01/2009, 16h15

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo