Skip to main content
 首页 » 编程设计

c#之取消可观察集合上的集合更改事件

2024年01月13日28Free-Thinker

如何取消可观察集合上的集合更改事件? 当我的集合发生变化时,它会调用第三方 dll 上的方法。这些方法可能会失败,也可能不会失败。

如果他们失败了,我不想将项目添加到集合中或从集合中删除。从名称上看,似乎是在添加或删除某些内容后触发了集合更改事件,但我该如何实现我的功能?

请您参考如下方法:

为时已晚,但它可能对其他人有帮助:

class ExtendedObservableCollection<T> : ObservableCollection<T> 
{ 
    private bool _suppressNotification = false; 
 
    public bool AllowNotifications { get { return _suppressNotification; } } 
 
    protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e) 
    { 
        if (!_suppressNotification) 
            base.OnCollectionChanged(e); 
    } 
 
    protected override void OnPropertyChanged(PropertyChangedEventArgs e) 
    { 
        if (!_suppressNotification) 
            base.OnPropertyChanged(e); 
    } 
 
    public void ActivateNotifications() 
    { 
        _suppressNotification = false; 
    } 
 
    public void DesactivateNotifications() 
    { 
        _suppressNotification = true; 
    } 
 
    public void AddRange(IEnumerable<T> list) 
    { 
        if (list == null) 
            throw new ArgumentNullException("list"); 
 
        _suppressNotification = true; 
 
        foreach (T item in list) 
        { 
            Add(item); 
        } 
        _suppressNotification = false; 
        OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add)); 
    } 
 
 
}