访问绑定到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匹配.
I have an ObservableCollection bound to a WPF DataGrid in which MyClass has a Boolean flag indicating if item has been seen or not. If the item in the DataGrid is selected I want to set the MyClass.Seen property to true to indicate that it was viewed. Initially, the SelectedIndex of the DataGrid matches to the index of the ObservableCollection but if I ever sort the DataGrid using any of the various columns that it displays, the SelectedIndex no longer matches with the ObservableCollection.
到目前为止,我一直在遍历ObservableCollection,将MyClass中的值与DataGrid的SelectedIndex行的列值进行比较以找到匹配项.在引用DataGrid的SelectedIndex指向我指向ObservableCollection中正确的项目时,是否有更好的方法来实现这一点?
Up until now I have been looping thru the ObservableCollection comparing a value in MyClass to a column value of the DataGrid's SelectedIndex row to find a match. Is there a better way to accomplish this where referencing the SelectedIndex of the DataGrid points me to the correct item in the ObservableCollection?
推荐答案
而不是使用SelectedIndex
,您是否尝试过使用SelectedItem
或SelectedValue
?如果DataGrid
的ItemSource
设置为您的ObservableCollection
,则这些属性应直接指向所选的包含对象.
Rather than using SelectedIndex
, have you tried using SelectedItem
or SelectedValue
? If the DataGrid
's ItemSource
is set to your ObservableCollection
, then those properties should point directly to the selected contained object.
这篇关于访问绑定到WPF DataGrid的ObservableCollection中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!