microsoft / microsoft/microsoft-ui-xaml
TreeViewItem Collapses When Its Items Are Removed Until Empty in WinUI 3
- Dominant language
- C++
- Stars
- 8.4k
- Forks
- 942
- Avg merge
- 2d 7h
- Merged PRs (30d)
- 105
Description
### Describe the bug
Removing items sequentially from an expanded `TreeViewItem` until it is empty causes it to collapse. When items are added back, the parent `TreeViewItem` unexpectedly **remains collapsed**. This behavior occurs when the underlying `ObservableCollection` emits a `Remove` event for the last item.

**A Workaround**
If the last item is removed using the `Clear` method instead of `RemoveAt`, the `ObservableCollection` will emit the `Reset` event, which **will not** cause this issue. However, I still find it very unintuitive and it is particularly inconvenient when the source collection is controlled by a 3rd party library, like DynamicData.

FYI: if the parent `TreeViewItem` was collapsed before calling `Clear`, it will **remain collapsed after as expected**, so there seems to be no issue with that.
### Steps to reproduce the bug
1. Run the project: https://github.com/datskiy/TreeViewCollapsingIssue
2. Observe that the parent `TreeViewItem` is collapsed and start clicking the **'Remove Item'** button until all of them are removed.
3. Click the **'Restore Item'** button to add one item back and observe that the parent `TreeViewItem` **remains collapsed**.
### Expected behavior
The parent `TreeViewItem` should automatically expand when items are re-added to the source `ObservableCollection` if it was expanded **before** removing all the items, like it happens when the `Clear` method is used.
### Screenshots
_No response_
### NuGet package version
WinUI 3 - Windows App SDK 1.6.3: 1.6.241114003
### Windows version
Windows 11 (24H2): Build 26100
### Additional context
The `IsExpanded` property is set as `True` in XAML.
Source code: https://github.com/datskiy/TreeViewCollapsingIssue
Contributor guide
Research direction
Start with the linked TreeViewCollapsingIssue reproduction project and reproduce the sequence using Remove Item until the collection is empty, then Restore Item. Trace how the Remove notification for the last item affects the TreeViewItem's expanded state, comparing it with the Reset notification from Clear. Done means an item re-added after sequential removal restores the prior expanded state.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- cpp
- Domain
- desktop
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100