英文:
How to update bound values immediately in WPF DataGrid when editing cells?
问题
我正在使用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中的单元格时立即更新?
英文:
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?
答案1
得分: 2
我找到了一个非常简单的解决方案,通过将可编辑列的 UpdateSourceTrigger
更改为 PropertyChanged
,可以完美地解决我的简单应用程序的问题。
<DataGrid ItemsSource="{Binding MyCollection}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Column1" Binding="{Binding Path=Property1, UpdateSourceTrigger=PropertyChanged}" />
<!-- 如果需要更多列 -->
</DataGrid.Columns>
</DataGrid>
英文:
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>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论