WPF DataGrid CellEditEnded事件

时间:2012-04-30 18:09:21

标签: c# wpf wcf data-binding datagrid

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

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

每次用户提交对集合的更改时,最好的方法是什么。

更新

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

4 个答案:

答案 0 :(得分:7)

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

见下文

<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将在目标属性更改时立即更改属性源。

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

答案 1 :(得分:0)

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

    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! */  }
    }

答案 2 :(得分:0)

我改用了“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>

答案 3 :(得分:-1)

您应该只在ObservableCollection的{​​{1}}事件中添加事件处理程序。

代码段:

CollectionChanged

_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时,这意味着您的列表中的对象已被替换。在应用更改后,当然会触发此事件

玩得开心!

相关问题