1
votes

I am working on a project where I have implemented MVVM for WPF desktop application. I have a situation where I wanted to make Datagrid editable just like old MS Access table list view. I am binding Datagrid's ItemsSource to ObservableCollection Where Member implements INPC. Now I want to allow users to update member by clicking on any cell of the column, when they navigate to other row or Lost Focus the data should be validated and then saved to the DB.

How to capture such events in my ViewModel and how can I achieve this simple functionality?

2

2 Answers

0
votes

You can trigger the "save" actions by binding the SelectedItem of the grid to a property on your viewmodel, and in the setter of the property you can save the previously selected item before replacing it with the newly selected item, in brief pseudo code it would look something like this:

public MyDataObject SelectedItem
{
    get { return _selectedItem; }
    set 
    {
        if (value != _selectedItem)
        {
            SaveMyItem(_selectedItem);
            _selectedItem = value;
            OnPropertyChanged("SelectedItem");
        }
    }
}

private MyDataObject _selectedItem;
<DataGrid ItemsSource="{Binding MyCollection}" SelectedItem="{Binding SelectedItem, UpdateSourceTrigger=PropertyChanged}" ...etc... />

Of course you may need to tailor this approach somewhat - if it takes a noticeable amount of time to save the modified item then you will want to do that on a background thread. If you specify the validation as part of the column bindings on the grid, the user will not be able to select and edit a new row until the data has correctly validated.

0
votes

I would use Linq to Sql and bind the datagrid ItemsSource directly to the table you want. This will handle all the change tracking for you and will also save to the database when you simply call SubmitChanges (which you can do whenever the selectedItem changes, see slugster's answer).