gpt4 book ai didi

c# - ObservableCollection 没有注意到其中的 Item 发生变化(即使使用 INotifyPropertyChanged)

转载 作者:IT王子 更新时间:2023-10-29 03:31:19 26 4
gpt4 key购买 nike

有谁知道为什么这段代码不起作用:

public class CollectionViewModel : ViewModelBase {  
public ObservableCollection<EntityViewModel> ContentList
{
get { return _contentList; }
set
{
_contentList = value;
RaisePropertyChanged("ContentList");
//I want to be notified here when something changes..?
//debugger doesn't stop here when IsRowChecked is toggled
}
}
}

public class EntityViewModel : ViewModelBase
{

private bool _isRowChecked;

public bool IsRowChecked
{
get { return _isRowChecked; }
set { _isRowChecked = value; RaisePropertyChanged("IsRowChecked"); }
}
}

ViewModelBase 包含 RaisePropertyChanged 等的所有内容,它适用于除此问题之外的所有其他内容..

最佳答案

这是一个插入类,它是 ObservableCollection 的子类,当列表项的属性发生变化时实际上会引发重置操作。它强制所有项目实现 INotifyPropertyChanged

这里的好处是您可以将数据绑定(bind)到此类,并且您的所有绑定(bind)都将随着项目属性的更改而更新。

public sealed class TrulyObservableCollection<T> : ObservableCollection<T>
where T : INotifyPropertyChanged
{
public TrulyObservableCollection()
{
CollectionChanged += FullObservableCollectionCollectionChanged;
}

public TrulyObservableCollection(IEnumerable<T> pItems) : this()
{
foreach (var item in pItems)
{
this.Add(item);
}
}

private void FullObservableCollectionCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null)
{
foreach (Object item in e.NewItems)
{
((INotifyPropertyChanged)item).PropertyChanged += ItemPropertyChanged;
}
}
if (e.OldItems != null)
{
foreach (Object item in e.OldItems)
{
((INotifyPropertyChanged)item).PropertyChanged -= ItemPropertyChanged;
}
}
}

private void ItemPropertyChanged(object sender, PropertyChangedEventArgs e)
{
NotifyCollectionChangedEventArgs args = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, sender, sender, IndexOf((T)sender));
OnCollectionChanged(args);
}
}

关于c# - ObservableCollection 没有注意到其中的 Item 发生变化(即使使用 INotifyPropertyChanged),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1427471/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com