From b4d615b95574f7a4969f7ebc6c5d17f533136985 Mon Sep 17 00:00:00 2001 From: Steven Kirk Date: Tue, 25 Aug 2020 12:39:53 +0200 Subject: [PATCH] Use CollectionChangedEventManager in ItemsControl. --- src/Avalonia.Controls/ItemsControl.cs | 30 +++++++++++++++++++-------- 1 file changed, 21 insertions(+), 9 deletions(-) diff --git a/src/Avalonia.Controls/ItemsControl.cs b/src/Avalonia.Controls/ItemsControl.cs index 1aa7945901..a3dfe33641 100644 --- a/src/Avalonia.Controls/ItemsControl.cs +++ b/src/Avalonia.Controls/ItemsControl.cs @@ -18,7 +18,7 @@ namespace Avalonia.Controls /// /// Displays a collection of items. /// - public class ItemsControl : TemplatedControl, IItemsPresenterHost + public class ItemsControl : TemplatedControl, IItemsPresenterHost, ICollectionChangedListener { /// /// The default value for the property. @@ -53,7 +53,6 @@ namespace Avalonia.Controls private IEnumerable _items = new AvaloniaList(); private int _itemCount; private IItemContainerGenerator _itemContainerGenerator; - private IDisposable _itemsCollectionChangedSubscription; /// /// Initializes static members of the class. @@ -150,6 +149,19 @@ namespace Avalonia.Controls ItemContainerGenerator.Clear(); } + void ICollectionChangedListener.PreChanged(INotifyCollectionChanged sender, NotifyCollectionChangedEventArgs e) + { + } + + void ICollectionChangedListener.Changed(INotifyCollectionChanged sender, NotifyCollectionChangedEventArgs e) + { + } + + void ICollectionChangedListener.PostChanged(INotifyCollectionChanged sender, NotifyCollectionChangedEventArgs e) + { + ItemsCollectionChanged(sender, e); + } + /// /// Gets the item at the specified index in a collection. /// @@ -315,12 +327,14 @@ namespace Avalonia.Controls /// The event args. protected virtual void ItemsChanged(AvaloniaPropertyChangedEventArgs e) { - _itemsCollectionChangedSubscription?.Dispose(); - _itemsCollectionChangedSubscription = null; - var oldValue = e.OldValue as IEnumerable; var newValue = e.NewValue as IEnumerable; + if (oldValue is INotifyCollectionChanged incc) + { + CollectionChangedEventManager.Instance.RemoveListener(incc, this); + } + UpdateItemCount(); RemoveControlItemsFromLogicalChildren(oldValue); AddControlItemsToLogicalChildren(newValue); @@ -418,11 +432,9 @@ namespace Avalonia.Controls PseudoClasses.Set(":empty", items == null || items.Count() == 0); PseudoClasses.Set(":singleitem", items != null && items.Count() == 1); - var incc = items as INotifyCollectionChanged; - - if (incc != null) + if (items is INotifyCollectionChanged incc) { - _itemsCollectionChangedSubscription = incc.WeakSubscribe(ItemsCollectionChanged); + CollectionChangedEventManager.Instance.AddListener(incc, this); } }