繁体   English   中英

WPF DataGrid CellEditEnded 事件

[英]WPF DataGrid CellEditEnded event

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

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

了解用户每次对集合进行更改时的最佳方式是什么。

更新

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

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

见下文

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

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

如果您需要知道编辑的 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! */  }
    }

我改用了“ 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.ActionReplace ,这意味着您的列表中的一个对象已被替换。 此事件当然是在应用更改后触发的

玩得开心!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM