I have a DataGrid simplified looking like this:
<DataGrid AutoGenerateColumns="False"
ItemsSource="{Binding Parts}"
SelectedItem="{Binding SelectedPart}" >
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Path=Name, Mode=TwoWay}" />
<DataGridTemplateColumn Header="PartType" >
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}, Path=DataContext.PartTypes}"
SelectedItem="{Binding PartType, Mode=TwoWay, UpdateSourceTrigger=LostFocus}" />
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding PartType}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
My ViewModel looks something like this:
public class PartListViewModel
{
private ObservableCollection<Part> _parts;
public ObservableCollection<Part> Parts
{
get { return _parts; }
set
{
_parts = value;
OnPropertyChanged("Parts");
}
}
private Part _selectedPart;
public Part SelectedPart
{
get { return _selectedPart; }
set
{
_selectedPart = value;
OnPropertyChanged("SelectedPart");
}
}
}
Now I want changes to datagrid cells being stored immediately to the database. How to do that in MVVM?
Currently I listen to the OnCellEditEnding
event of the DataGrid and save the record in the code-behind. But that is pretty ugly:
private void DataGrid_OnCellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
var viewModel = (PartListViewModel) DataContext;
viewModel.SavePart((Part) e.Row.Item);
}