我TrulyObservableCollection
在 WPF DataGrid 中使用 a 作为数据源。我的班级PropertyChange
正确地实现了事件(属性更改时我会收到通知)。该CollectionChanged
事件也被触发。但是,我的问题在于PropertyChanged
事件与CollectionChanged
事件之间的联系。我可以在PropertyChanged
事件中看到哪个项目被更改(在这种情况下是sender
对象),但是我似乎无法找到一种方法来查看在CollectionChanged
事件中更改了哪个项目。sender
对象是整个集合。查看活动中哪个项目发生变化的最佳方式是什么CollectionChanged
?相关的代码片段如下。感谢您的帮助,如果需要澄清,请告诉我。
设置集合的代码:
private void populateBret()
{
bretList = new TrulyObservableCollection<BestServiceLibrary.bretItem>(BestClass.BestService.getBretList().ToList());
bretList.CollectionChanged += bretList_CollectionChanged;
dgBretList.ItemsSource = bretList;
dgBretList.Items.Refresh();
}
void bretList_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
//Do stuff here with the specific item that has changed
}
集合中使用的类:
public class bretItem : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private int _blID;
public string _blGroup;
[DataMember]
public int blID
{
get { return _blID; }
set
{
_blID = value;
OnPropertyChanged("blID");
}
}
[DataMember]
public string blGroup
{
get { return _blGroup; }
set
{
_blGroup = value;
OnPropertyChanged("blGroup");
}
}
protected void OnPropertyChanged (String name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
TrulyObservableCollection 类
public class TrulyObservableCollection<T> : ObservableCollection<T> where T : INotifyPropertyChanged
{
public TrulyObservableCollection()
: base()
{
CollectionChanged += new NotifyCollectionChangedEventHandler(TrulyObservableCollection_CollectionChanged);
}
public TrulyObservableCollection(List<T> list)
: base(list)
{
foreach (var item in list)
{
item.PropertyChanged += new PropertyChangedEventHandler(item_PropertyChanged);
}
CollectionChanged += new NotifyCollectionChangedEventHandler(TrulyObservableCollection_CollectionChanged);
}
void TrulyObservableCollection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null)
{
foreach (Object item in e.NewItems)
{
(item as INotifyPropertyChanged).PropertyChanged += new PropertyChangedEventHandler(item_PropertyChanged);
}
}
if (e.OldItems != null)
{
foreach (Object item in e.OldItems)
{
(item as INotifyPropertyChanged).PropertyChanged -= new PropertyChangedEventHandler(item_PropertyChanged);
}
}
}
void item_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
NotifyCollectionChangedEventArgs a = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset);
OnCollectionChanged(a);
}
}
编辑:
如果设置item_PropertyChanged
为. 这导致and为空,因此在这种情况下我无法获得更改的项目。我不能使用,因为 Datagrid 已使用附加项目进行了更新。我似乎也无法开始工作以获取更改的项目。NotifyCollectionChangedEventArgs
NotifyCollectionChangedAction.Reset
OldItems
NewItems
.Add
.Replace