WPF DataGrid CellEditEnded event

本文关键字:event CellEditEnded DataGrid WPF | 更新日期: 2023-09-27 18:32:40

我希望知道用户每次编辑我的 DataGrid 单元格的内容。有 CellEditEnding 事件,但它是在对集合进行任何更改之前调用的,DataGrid 绑定到该集合。

我的数据网格绑定到 ObservableCollection<Item> ,其中Item是一个类,从 WCF mex 终结点自动生成。

了解用户每次向集合提交更改的最佳方法是什么。

更新

我尝试过 CollectionChanged 事件,当Item被修改时,它不会被触发。

WPF DataGrid CellEditEnded event

可以在数据网格的属性成员的绑定上使用UpdateSourceTrigger=PropertyChanged。这将确保在触发 CellEditEnd 时,更新已反映在可观察集合中。

见下文

<DataGrid SelectionMode="Single"
          AutoGenerateColumns="False"
          CanUserAddRows="False"
          ItemsSource="{Binding Path=Items}" // This is your ObservableCollection
          SelectedIndex="{Binding SelectedIndexStory}">
          <e:Interaction.Triggers>
              <e:EventTrigger EventName="CellEditEnding">
                 <cmd:EventToCommand PassEventArgsToCommand="True" Command="{Binding EditStoryCommand}"/> // Mvvm light relay command
               </e:EventTrigger>
          </e:Interaction.Triggers>
          <DataGrid.Columns>
                    <DataGridTextColumn Header="Description"
                        Binding="{Binding Name, UpdateSourceTrigger=PropertyChanged}" /> // Name is property on the object i.e Items.Name
          </DataGrid.Columns>
</DataGrid>

每当目标属性更改时,UpdateSourceTrigger = PropertyChanged 将立即更改属性源。

这将允许您捕获对项目的编辑,因为将事件处理程序添加到可观察集合更改事件不会为集合中对象的编辑触发。

如果需要知道编辑的 DataGrid 项是否属于特定集合,可以在 DataGrid 的 RowEditEnd 事件中执行以下操作:

    private void dg_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
    {
        // dg is the DataGrid in the view
        object o = dg.ItemContainerGenerator.ItemFromContainer(e.Row);
        // myColl is the observable collection
        if (myColl.Contains(o)) { /* item in the collection was updated! */  }
    }

我用了" CurrentCellChanged "。

    <DataGrid
        Grid.Row="1"
        HorizontalAlignment="Center"
        AutoGenerateColumns="True"
        AutoGeneratingColumn="OnAutoGeneratingColumn"
        ColumnWidth="auto"
        IsReadOnly="{Binding IsReadOnly}"
        ItemsSource="{Binding ItemsSource, UpdateSourceTrigger=PropertyChanged}">
        <b:Interaction.Triggers>
            <!--  CellEditEnding  -->
            <b:EventTrigger EventName="CurrentCellChanged">
                <b:InvokeCommandAction Command="{Binding CellEditEndingCmd}" />
            </b:EventTrigger>
        </b:Interaction.Triggers>
    </DataGrid>
你应该

ObservableCollectionCollectionChanged事件上添加一个事件处理程序。

代码片段:

_listObsComponents.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(ListCollectionChanged);
// ...

    void ListCollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {
        /// Work on e.Action here (can be Add, Move, Replace...)
    }

e.Action Replace 时,这意味着列表中的对象已被替换。当然,此事件是在应用更改后触发

玩得愉快!