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

huangapple go评论52阅读模式
英文:

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:

&lt;DataGrid ItemsSource=&quot;{Binding MyCollection}&quot; AutoGenerateColumns=&quot;True&quot;&gt;
&lt;/DataGrid&gt;

My ViewModel looks similar to this:

public class MyViewModel : INotifyPropertyChanged
{
    public ObservableCollection&lt;MyModel&gt; 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,可以完美地解决我的简单应用程序的问题。

&lt;DataGrid ItemsSource=&quot;{Binding MyCollection}&quot; AutoGenerateColumns=&quot;False&quot;&gt;
    &lt;DataGrid.Columns&gt;
        &lt;DataGridTextColumn Header=&quot;Column1&quot; Binding=&quot;{Binding Path=Property1, UpdateSourceTrigger=PropertyChanged}&quot; /&gt;
        &lt;!-- 如果需要更多列 --&gt;
    &lt;/DataGrid.Columns&gt;
&lt;/DataGrid&gt;
英文:

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

&lt;DataGrid ItemsSource=&quot;{Binding MyCollection}&quot; AutoGenerateColumns=&quot;False&quot;&gt;
    &lt;DataGrid.Columns&gt;
        &lt;DataGridTextColumn Header=&quot;Column1&quot; Binding=&quot;{Binding Path=Property1, UpdateSourceTrigger=PropertyChanged}&quot; /&gt;
        &lt;!-- More columns if needed --&gt;
    &lt;/DataGrid.Columns&gt;
&lt;/DataGrid&gt;

huangapple
  • 本文由 发表于 2023年5月8日 01:29:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76195348.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定