2012-04-30 68 views
3

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

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

什么是每次用户提交集合更改时知道的最佳方式。

UPDATE

我试过CollectionChanged事件,结束的时候Item被修改了它不会被触发。

回答

-1

您只需在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,这意味着你的列表的对象已经被更换。这个事件当然是在应用更改后触发的

玩得开心!

+0

事实上,在我发布这个问题之前,我就是这么做的。当用户修改集合时,CollectionChanged事件不会被触发 –

+0

这不是您的答案,但CollectionChanged仅在以某种方式添加或删除项目时才报告。有可能网格让你修改一个项目而不会真正改变集合本身,所以不会触发上述事件。 – NestorArturo

+0

Woops,是的,误解在这里,当一个完整的'Item'会改变时(即你放置一个新的Item()而不是前一个)''CollectionChanged'会被触发。你需要你的'Item'类来实现'INotifyPropertyChanged',如果你想抓住每一个修改:) – Damascus

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

您可以在属性成员的结合使用UpdateSourceTrigger=PropertyChanged为datagrid。这将确保当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会立即改变属性源只要目标属性更改。

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

+0

谢谢你! – Richard