C# – WPF datagrid with MVVM

cdatagridmvvmwpf

I'm trying to bind a datagrid in WPF to my ViewModel so that it will update any cell changes to the database as well as allow the user to delete rows and add new rows. I've got part of it working but can't find a ELEGANT solution for the ADD and modify.
here is the xaml

<DataGrid AutoGenerateColumns="false" HorizontalAlignment="Left" Margin="26,41,0,0" Name="dataGrid1"   
              ItemsSource="{Binding Path=GetAllItems}" Height="200" VerticalAlignment="Top" Width="266" >
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding Path=ItemListID}" Header="ID" Visibility="Hidden"/>
            <DataGridTextColumn Binding="{Binding Path=ItemName}" Header="Name" Width="4*" />
            <DataGridCheckBoxColumn Binding="{Binding Path=IsActive}" Header="Active" Width="*"  />
        </DataGrid.Columns>

then in my view model method

private ObservableCollection< ItemsList> getAllItems()
{
    using (var context = new InspectorGeneralEntities())
    {
        var query = from I in context.ItemsLists
                    select I;

        var item = new ObservableCollection<ItemsList>(query.ToList());
        return item;
    }
}

Deleting a row or modifying a row on the datagrid does not flow onto the database.

a) what other binding do i need to create in the xaml code that will detect these events

b) How do i detect a removed record or modified item in the view model so that I can update the datacontext if it won't automatically.

Best Answer

Just subscribe to the CollectionChanged event of your ObservableCollection. The event handler receives an instance of the NotifyCollectionChangedEventArgs class which contains a property 'Action' describing if rows have been added or removed. It also contains lists of the rows that have been added ('NewItems') or removed ('OldItems'). That should give you enough information to update your database.

You could implement INotifyPropertyChanged in your row ViewModel (class ItemsList I guess) and then subscribe to it, to find out if a row is dirty and needs to be updated in the database. The interface consists of a single event PropertyChanged that is to be raised in the property setters of your ViewModel whenever a value changes.

You're right the NotifyCollectionChanged event comes too early for an immediate insert to the database. But you can flag the row as 'inserted' in the event handler and insert it as soon as the last property changed event (see above) required to complete the row occurs.

Related Topic