如何在编辑单元格时立即更新 WPF DataGrid 中的绑定值?

问题描述 投票:0回答:1

我正在 MVVM 应用程序中使用 WPF DataGrid。我已将 DataGrid 绑定到我的 ViewModel 中的 ObservableCollection。目前,当用户编辑 DataGrid 中的单元格时,绑定值仅在单元格失去焦点时更新。

这是我的 DataGrid 的 XAML 代码:

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

我的 ViewModel 看起来与此类似:

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

如何在用户编辑 DataGrid 中的单元格时立即更新绑定值?

c# wpf mvvm datagrid
1个回答
0
投票

我找到了一个非常简单的解决方案,只需将可编辑列的

UpdateSourceTrigger
更改为
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>
© www.soinside.com 2019 - 2024. All rights reserved.