简体   繁体   中英

Apply changes to Model when a row of DataGrid is changed using MVVM

I have a simple scenario, I've a DataGrid which is bound to an ObservableCollection I want user to be able to add a new ComplexType Item (which means a row) on the fly. by one the fly, I mean Data model needs to be updated whenever user has finished entring row data. the problem is ViewModel's binding is not called when a row has changed or added. Does anyone has any idea how to handle this situation in ViewModel. My intuition tells me it should be very easy in MVVM but i'm stuck! here is my xaml:

<DataGrid x:Name="gd_Users"  CanUserDeleteRows="True" CanUserAddRows="True" CanUserAddRows="True" AutoGenerateColumns="False" ItemsSource="{Binding UserCollection,Mode=TwoWay}" SelectedItem="{Binding SelectedUser}" Margin="1,5" Grid.Column="1">
    <DataGrid.Columns>
        <DataGridTextColumn Header="header1" Width="50"  Binding="{Binding u_Code}"/>
        <DataGridTextColumn Header="Header2" Width="100" Binding="{Binding u_FirstName}"/>
        <DataGridTextColumn Header="header3" Width="150" Binding="{Binding u_LastName}" />
    </DataGrid.Columns>
</DataGrid>

PS:I dont want to use event such as "RowEditEnding" in code behind

You need to implement IEditableObject in the view model for data row:

public class RowViewModel : IEditableObject
{
    public int Id { get; set; }
    public string Name { get; set; }

    public void BeginEdit()
    {
    }

    public void CancelEdit()
    {
    }

    public void EndEdit()
    {
        // this method is called, when user has ended editing
        // TODO: call service layer to update model
    }
}

DataGrid knows about this interface, and if VM implements it, DataGrid calls its methods.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM