WPF:当 ItemsSource 的内容发生更改时,ListBox 是否会引发事件?



我有一个ListBox,其ItemSource绑定到ObservableCollection

我在此ListBox中激活了附加行为。此附加行为挂钩到ItemsSource属性的更改事件中。触发此事件时,它会检查新的ItemsSource值是否为INotifyCollectionChanged类型,如果是,它也将挂钩到其CollectionChanged事件中。

但是当这个事件被触发时,我再也无法访问ListBox,只能访问ObservableCollection.

ListBox中是否存在在其ItemsSource内容发生更改时触发的事件?这样我就可以访问ListBox

所以,没有这样的事件,但是,我们可以使用Items属性来解决这个问题。

首先,我们需要订阅Items属性的CollectionChanged事件:

((INotifyCollectionChanged)listBox.Items).CollectionChanged += Handler

现在我们可以访问ItemCollection

void Handler(object sender, NotifyCollectionChangedEventArgs e) 
{ 
var items = (ItemCollection)sender; 
}

正如对此问题的回答所表明的那样,ItemCollection的父ItemsControl没有公共访问器。但是,这段参考源向我们展示了框架以该字段和此方便属性的形式具有它。现在我们只需要参考它。 你可以通过使用委托来加快速度(显然你会将它们缓存为静态字段,下面的代码用于演示目的(。

var getterMethodInfo = typeof(ItemCollection).GetProperty("ModelParent", BindingFlags.NonPublic | BindingFlags.Instance).GetGetMethod(true);
var getterDelegate = (Func<ItemCollection, DependencyObject>)Delegate.CreateDelegate(typeof(Func<ItemCollection, DependencyObject>), getterMethodInfo);
var listBox = (ListBox)getterDelegate(items);

最新更新