I'm trying to figure out how to handle changes in a data grid cell while keeping within the MV开发者_如何学编程VM 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?
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());
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;
)
精彩评论