Skip to content

TreeView SelectionChanged event doesn't report deselected items, and is inconsistent with ListBox's behavior #22116

Description

@pwitvoet

Describe the bug

When selecting an item in a TreeView, and then selecting another item (which deselects the first item), the SelectionChanged event only reports that the second item was added to the selection. It does not report that the first item was removed from the selection. This happens regardless of which SelectionMode is used.

The exact same setup with a ListBox does report deselected items. A ListBox also raises a single SelectionChanged event for a select-all action, whereas a TreeView will fire a SelectionChanged event for every item that gets selected, which is less efficient. TreeView also doesn't support ISelectionModel, so it looks like there is currently no efficient way to handle big selection changes.

To Reproduce

axaml:

<StackPanel Orientation="Vertical">
    <TreeView x:Name="ItemsTreeView" SelectionMode="Multiple" SelectionChanged="TreeView_SelectionChanged" Margin="5" />
    <TextBlock x:Name="LogTextBlock" Margin="5" />
</StackPanel>

code behind:

public MainWindow()
{
    InitializeComponent();
    ItemsTreeView.ItemsSource = new string[] { "Apple", "Banana", "Citrus", "Pear" };
}

private void TreeView_SelectionChanged(object? sender, SelectionChangedEventArgs e)
{
    LogTextBlock.Text += $"Added: {e.AddedItems.Count}, removed: {e.RemovedItems.Count} (selected: {ItemsTreeView.SelectedItems.Count})\n";
}

When selecting an item, and then another one, the log reads:

Added: 1, removed: 0 (selected: 1)
Added: 1, removed: 0 (selected: 1)

When selecting all (Ctrl+A), the log reads:

Added: 1, removed: 0 (selected: 1)
Added: 1, removed: 0 (selected: 2)
Added: 1, removed: 0 (selected: 3)
Added: 1, removed: 0 (selected: 4)

Expected behavior

With the above example, the expected log output would be:

Added: 1, removed: 0 (selected: 1)
Added: 1, removed: 1 (selected: 1)

When selecting all (Ctrl+A), the expected log output is:

Added: 4, removed: 0 (selected: 4)

Avalonia version

12.1.1

OS

Windows

Additional context

No response

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions