Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you handle data grid cell changes with MVVM?

Tags:

mvvm

wpf

I'm trying to figure out how to handle changes in a data grid cell while keeping within the MVVM design pattern. When the user changes the value in a cell, I have to go off and change a bunch of files based on the new cell value. I know how I could easily do this with code behind, but is there a cleaner, more MVVM-esque way to do this with command bindings?

like image 548
blachniet Avatar asked Jun 15 '11 13:06

blachniet


2 Answers

Usually i do this with interaction triggers from Galasoft.

 <DataGrid IsReadOnly="False">
            <e:Interaction.Triggers>
                <e:EventTrigger EventName="CellEditEnding">
                    <GalaSoft_MvvmLight_Command:EventToCommand PassEventArgsToCommand="True" Command="{Binding CellEditEndingCommand}"/>
                </e:EventTrigger>
            </e:Interaction.Triggers>
        <DataGrid.Columns>
               ...                        
    </DataGrid.Columns>
</DataGrid>

Then inside ViewModel you create generic RelayCommand where generic type is type of corresponding EventArgs.

RelayCommand<DataGridCellEditEndingEventArgs> CellEditEndingCommand {get; set;}

Initialization:

CellEditEndingCommand = new RelayCommand<DataGridCellEditEndingEventArgs>(args=>DoSomething());
like image 96
Vladimir Nani Avatar answered Oct 27 '22 01:10

Vladimir Nani


Let's assume your DataGrid'sItemsSource is bound, TwoWay-mode, to something in your ViewModel, let's call it CustomObject or whatever.

Let's assume then that a specific DataGridCell is bound to a Property named SomeProperty, which is declared as follows:

private string someProperty;
public string SomeProperty {
  get { return someProperty; }
  set {
    someProperty = value;
    //Fire OnPropertyChanged here
  }
}

Put a breakpoint just on the set. Then, modify the cell in your View : the breakpoint will be reached.

This allows you to simulate an event: each time the set is called, it means the cell is gonna change, do whatever you want now with the changing process (you can for example test the new value, by testing on value, or keep the last value, by saving someProperty somewhere before the line someProperty = value; )

like image 21
Damascus Avatar answered Oct 27 '22 00:10

Damascus