Skip to content

InvalidOperationException when SelectedItem changes in ObservableCollection #20642

@alexandrehtrb

Description

@alexandrehtrb

Describe the bug

Avalonia 11.3.11
.NET 10
Windows 11 23H2 x64

I am running some UI tests and this bug shows up on Visual Studio. It doesn't crash the app, but this wasn't happening with the previous Avalonia version (11.0.5).
Seems related to SelectedItem and SelectedItems binding in a TreeView.
When I remove an item from an ObservableCollection bound to a TreeView, this Exception arises:

System.InvalidOperationException: 'Cannot change ObservableCollection during a CollectionChanged event.'

Image

XAML:

<TreeView
    x:Name="itemsTree"
    Margin="0 40 0 20"
    ItemsSource="{Binding Items}"
    SelectedItem="{Binding CollectionGroupSelectedItem, Mode=TwoWay}"
    SelectedItems="{Binding CollectionGroupSelectedItems, Mode=TwoWay}"
    SelectionMode="Multiple"
    ScrollViewer.HorizontalScrollBarVisibility="Disabled"
    Classes="sidebar DragAndDrop CollectionOrganizationItemDragAndDrop">

ViewModel:

public override ObservableCollection<CollectionViewModel> Items { get; }

public ObservableCollection<CollectionOrganizationItemViewModel> CollectionGroupSelectedItems { get; }

private CollectionOrganizationItemViewModel? collectionGroupSelectedItemField;
public CollectionOrganizationItemViewModel? CollectionGroupSelectedItem
{
    get => this.collectionGroupSelectedItemField;
    set
    {
        this.RaiseAndSetIfChanged(ref this.collectionGroupSelectedItemField, value);
        this.onCollectionsGroupItemSelected(this.collectionGroupSelectedItemField);
    }
}

private readonly Action<CollectionOrganizationItemViewModel?> onCollectionsGroupItemSelected;

To Reproduce

Expected behavior

No response

Avalonia version

11.3.11

OS

Windows

Additional context

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions