Search code examples
c#wpfmvvmdatagrid

How to update bound values immediately in WPF DataGrid when editing cells?


I am working with a WPF DataGrid in an MVVM application. I have bound the DataGrid to an ObservableCollection in my ViewModel. Currently, when a user edits a cell in the DataGrid, the bound values only update when the cell loses focus.

Here is the XAML code for my DataGrid:

<DataGrid ItemsSource="{Binding MyCollection}" AutoGenerateColumns="True">
</DataGrid>

My ViewModel looks similar to this:

public class MyViewModel : INotifyPropertyChanged
{
    public ObservableCollection<MyModel> MyCollection { get; set; } = new();
}

How can I make the bound values update immediately as the user edits the cells in the DataGrid?


Solution

  • I found a very simple solution that works perfectly for my simple application by just changing the UpdateSourceTrigger of the editable column to PropertyChanged.

    <DataGrid ItemsSource="{Binding MyCollection}" AutoGenerateColumns="False">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Column1" Binding="{Binding Path=Property1, UpdateSourceTrigger=PropertyChanged}" />
            <!-- More columns if needed -->
        </DataGrid.Columns>
    </DataGrid>