简体   繁体   English

更改集合时触发方法

[英]Fire a method when collection is changed

I have a binding that uses this collection: 我有一个使用此集合的绑定:

private RangeObservableCollection<Item> _allItems;

public RangeObservableCollection<Item> AllItems
            { 
                get { return _allItems; }
                set { _allItems = value; }
            }

RangeObservarbleCollection is a collection that throws only one notification that the collection was changed when AddRange method is called. RangeObservarbleCollection是一个集合,仅在调用AddRange方法时仅抛出一个集合已更改的通知。

I have another collection whose items depend on the items of the AllItems collection. 我有另一个集合,其项目取决于AllItems集合的项目。

private RangeObservableCollection<Item> _commonItems;

I want whenever the AllItems collection gets changed to fire a method that does some calculations and changes the items in the CommonItems collection. 我希望每当AllItems集合被更改为触发一个方法,该方法执行一些计算并更改CommonItems集合中的项目。 I tried to fire it inside the set method for the AllItems collection but the Value is of type collection not of type Item. 我尝试在AllItems集合的set方法中触发它,但Value的类型集合不是Item类型。

You can attach an event on to the collection like this: 您可以将事件附加到集合上,如下所示:

_allItems.CollectionChanged += new NotifyCollectionChangedEventHandler(_allItems_CollectionChanged)

protected void _allItems_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
     switch (e.Action)
         {
             case NotifyCollectionChangedAction.Add:
                //do stuff;
                 break;
             case NotifyCollectionChangedAction.Remove:
                //do stuff
                 break;
         }

}

You will want to attach to the event on the AllItems collection when setting the property, and detach when clearing it. 您需要在设置属性时附加到AllItems集合上的事件,并在清除它时分离。 Then fire your event from within the handler for the AllItems event. 然后从AllItems事件的处理程序中激活您的事件。

 public RangeObservableCollection<Item> AllItems { get { return _allItems; } set { if (_allItems != null) { _allItems.CollectionChanged -= AllItems_CollectionChanged; } _allItems = value; } if (_allItems != null) { _allItems.CollectionChanged +-= AllItems_CollectionChanged; } } private void AllItems_CollectionChanged(object sender, CollectionChangedEventArgs e) { OnCollectionChanged(e); } private void OnCollectionChanged(CollectionChangedEventArgs args) { EventHandler<CollectionChangedEventArgs> temp = CollectionChanged; if (temp != null) { temp.Invoke(this, args); } } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM