Sunday, April 12, 2015

MVVM Part 7

Making the DataGrid editable

To make the DataGrid editable we take off the IsReadOnly attribute, set CanUserAddRows and CanUserDeleteRows true, and set the EmployeeID read only. The new DataGrid definition looks like this...

<DataGrid Name="dg" Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="2" ItemsSource="{Binding Employees}" AutoGenerateColumns="False" CanUserAddRows="True" CanUserDeleteRows="True">
    <DataGrid.Columns>
        <DataGridTextColumn Header="ID" Binding="{Binding Path=EmployeeID}" IsReadOnly="True"/>
        <DataGridTextColumn Header="First Name" Binding="{Binding Path=FirstName}"></DataGridTextColumn>
        <DataGridTextColumn Header="Last Name" Binding="{Binding Path=LastName}"></DataGridTextColumn>
    </DataGrid.Columns>
</DataGrid>

If you run the application now you can modify Billy Bee and click [Save]. The changes are saved to the database. Try adding a new name in the blank row and clicking [Save]. Hmm - the new employee isn't saved to the database.

It turns out that we have to work harder to implement adding and removing rows. We need to provide an event handler for the ObservableCollection's CollectionChanged event to add new rows and remove deleted rows from the Model's employee table.

    1. At the end of the constructor add the following line of code...
        AddHandler Employees.CollectionChanged, AddressOf EmployeesChanged

    2. The event handler looks like this. Add it somewhere in the ViewModel class.
    Protected Sub EmployeesChanged(sender As Object, e As NotifyCollectionChangedEventArgs)
        Select Case e.Action
            Case NotifyCollectionChangedAction.Add
                For Each Emp As Employee In e.NewItems
                    Model.Employees.Add(Emp)
                Next
            Case NotifyCollectionChangedAction.Remove
                For Each Emp As Employee In e.OldItems
                    Model.Employees.Remove(Emp)
                Next
        End Select
    End Sub


No comments:

Post a Comment