From 6e8faab21775b43ad39b8545ab2e7f72027e453d Mon Sep 17 00:00:00 2001 From: Steven Kirk Date: Tue, 16 May 2023 19:13:13 +0200 Subject: [PATCH] Clear TreeView selection when items removed. --- src/Avalonia.Controls/TreeView.cs | 17 +++++++++++++++++ src/Avalonia.Controls/TreeViewItem.cs | 26 ++++++++++++++++++++++++++ 2 files changed, 43 insertions(+) diff --git a/src/Avalonia.Controls/TreeView.cs b/src/Avalonia.Controls/TreeView.cs index 0d5a453141..ef10dcdb22 100644 --- a/src/Avalonia.Controls/TreeView.cs +++ b/src/Avalonia.Controls/TreeView.cs @@ -293,6 +293,23 @@ namespace Avalonia.Controls return TreeItemFromContainer(this, container); } + private protected override void OnItemsViewCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e) + { + base.OnItemsViewCollectionChanged(sender, e); + + switch (e.Action) + { + case NotifyCollectionChangedAction.Remove: + case NotifyCollectionChangedAction.Replace: + foreach (var i in e.OldItems!) + SelectedItems.Remove(i); + break; + case NotifyCollectionChangedAction.Reset: + SelectedItems.Clear(); + break; + } + } + /// /// Subscribes to the CollectionChanged event, if any. /// diff --git a/src/Avalonia.Controls/TreeViewItem.cs b/src/Avalonia.Controls/TreeViewItem.cs index ccd4f89204..cf12c12447 100644 --- a/src/Avalonia.Controls/TreeViewItem.cs +++ b/src/Avalonia.Controls/TreeViewItem.cs @@ -1,9 +1,11 @@ using System; using System.Collections.Generic; +using System.Collections.Specialized; using System.Linq; using Avalonia.Controls.Metadata; using Avalonia.Controls.Mixins; using Avalonia.Controls.Primitives; +using Avalonia.Controls.Selection; using Avalonia.Controls.Templates; using Avalonia.Data; using Avalonia.Input; @@ -289,6 +291,30 @@ namespace Avalonia.Controls } } + private protected override void OnItemsViewCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e) + { + base.OnItemsViewCollectionChanged(sender, e); + + if (_treeView is null) + return; + + switch (e.Action) + { + case NotifyCollectionChangedAction.Remove: + case NotifyCollectionChangedAction.Replace: + foreach (var i in e.OldItems!) + _treeView.SelectedItems.Remove(i); + break; + case NotifyCollectionChangedAction.Reset: + foreach (var i in GetRealizedContainers()) + { + if (i is TreeViewItem tvi && tvi.IsSelected) + _treeView.SelectedItems.Remove(i.DataContext); + } + break; + } + } + private static int CalculateDistanceFromLogicalParent(ILogical? logical, int @default = -1) where T : class { var result = 0;