C# 更改集合时激发方法
我有一个使用此集合的绑定:C# 更改集合时激发方法,c#,wpf,binding,C#,Wpf,Binding,我有一个使用此集合的绑定: private RangeObservableCollection<Item> _allItems; public RangeObservableCollection<Item> AllItems { get { return _allItems; } set { _allItems = value; } } private r
private RangeObservableCollection<Item> _allItems;
public RangeObservableCollection<Item> AllItems
{
get { return _allItems; }
set { _allItems = value; }
}
private rangeobservecollection\u allItems;
公共范围可观测集合项目
{
获取{return\u allItems;}
设置{u allItems=value;}
}
RangeObserverBalCollection是一个集合,它在调用AddRange方法时仅抛出一个集合已更改的通知
我有另一个集合,其项目依赖于AllItems集合的项目
private RangeObservableCollection<Item> _commonItems;
private rangeobservecollection\u commonItems;
我希望每当AllItems集合发生更改时,都能触发一个方法,该方法执行一些计算并更改CommonItems集合中的项。我试图在AllItems集合的set方法中触发它,但该值的类型为collection,而不是Item。您可以将事件附加到集合上,如下所示:
_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;
}
}
设置属性时,您将希望附加到AllItems集合上的事件,清除属性时将其分离。然后从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);
}
}
public range observeablecollection AllItems
{
获取{return\u allItems;}
设置
{
如果(_allItems!=null)
{
_allItems.CollectionChanged-=allItems_CollectionChanged;
}
_allItems=value;}
如果(_allItems!=null)
{
_allItems.CollectionChanged+-=allItems_CollectionChanged;
}
}
私有void AllItems\u CollectionChanged(对象发送方,collectionchangedventargs e)
{
非集合更改(e);
}
CollectionChanged上的专用void(CollectionChangedEventArgs参数)
{
EventHandler temp=CollectionChanged;
如果(温度!=null)
{
临时调用(此参数为args);
}
}
我想你指的是价值,不是价值。您是说该值不是RangeObservableCollection类型?如果是这种情况,那么_allItems=value应该失败。不,我的意思是它不是Item类型