访问绑定到 WPF DataGrid 的 ObservableCollection 中的项目

Accessing items in ObservableCollection bound to WPF DataGrid

我有一个绑定到 WPF DataGrid 的 ObservableCollection,其中 MyClass 有一个布尔标志,指示是否已看到项目。如果选择了 DataGrid 中的项目,我想将 MyClass.Seen 属性 设置为 true 以指示它已被查看。最初,DataGrid 的 SelectedIndex 与 ObservableCollection 的索引匹配,但如果我使用它显示的各种列中的任何一个对 DataGrid 进行排序,SelectedIndex 将不再与 ObservableCollection 匹配。

到目前为止,我一直在遍历 ObservableCollection,将 MyClass 中的值与 DataGrid 的 SelectedIndex 行的列值进行比较以找到匹配项。在引用 DataGrid 的 SelectedIndex 将我指向 ObservableCollection 中的正确项目时,是否有更好的方法来完成此操作?

您是否尝试过使用 SelectedItemSelectedValue 而不是使用 SelectedIndex?如果 DataGridItemSource 设置为您的 ObservableCollection,则这些属性应直接指向所选包含的对象。