Skip to content

fix(treeview): Onboard TreeView to the WinUI port sync (2.7.0) - #26685

Open
MartinZikmund wants to merge 8 commits into
masterfrom
dev/mazi/onboard-treeview
Open

MartinZikmund wants to merge 8 commits into
masterfrom
dev/mazi/onboard-treeview

Conversation

@MartinZikmund

Copy link
Copy Markdown
Member

GitHub Issue: closes unoplatform/uno-private#2642

PR Type:

  • 🤖 Project automation (WinUI port sync onboarding, with port fixes)

What changed? 🚀

Onboards TreeView to the WinUI Port Sync, recorded at WinUI 2.7.0 (1b5b1a0ccc). The port is caught up from 1.4.2, reviewed line by line against 2.7.0, and its Uno workarounds are audited.

Mapping

Upstream Uno
controls/dev/TreeView src/Uno.UI/UI/Xaml/Controls/TreeView
controls/dev/TreeView/APITests, TestUI RuntimeTests/.../Controls/TreeView (*.mux.cs), SamplesApp.Samples/.../Controls/TreeView
controls/dev/TreeView/Strings src/Uno.UI/UI/Xaml/Controls/TreeView/Strings
TreeView.xaml, TreeViewItem.xaml, TreeView_themeresources.xaml the three FluentTheme/Resources/PriorityDefault files, as mirrors

Two corrections to the estimate in the issue: upstream does have a Strings folder (86 locales, the same set as Uno's and already identical, so it is mapped and nothing changed), and the TestUI pages were already ported, except TreeViewItemsSourceTestPage. The theme XAML is byte-for-byte upstream's, hence mirrors. InteractionTests are not mapped. Given_TreeView*.cs are Uno-written and stay outside the mapping.

Starting point

Headers: 22 files at winui3/release/1.4.2, 3 automation peers at 1.8.4, 3 theme files at 2.5.1, and TreeViewSelectionMode.cs at the WinUI 2 commit 96244e6. Starting point is 1.4.2, the tag most files agree on. 96244e6 predates the controls/dev layout and cannot be used; the enum matches the IDL. The peers and theme files were compared with 2.7.0 directly. Catch-up size: 16 files, +615 / −227.

Upstream changes 1.4.2 → 2.7.0

Ported

  • ViewModel.cpp/.h: IndexOf_OptimizedForRemove / GetCustomIndexOfFunction on both selection vectors, InsertAtCore_NoContainsCheck, InsertAt_NoContainsCheck, descendants unselected back to front → SelectedTreeNodeVector.cs, SelectedItemsVector.cs, TreeViewViewModel.cs. The search itself comes from Collections/Vector.h (outside the area, small) and is ported into ObservableVector<T>; the caller holds the search position so other vectors do not grow.
  • ViewModel.cpp, TreeView.cpp/.h: m_itemToNodeMap removed, GetAssociatedNode walks the tree → TreeViewViewModel.cs, TreeView.cs.
  • TreeViewItem.cpp/.h: m_expandContentTimer is a plain field → TreeViewItem.cs.
  • TreeViewList.cpp: binding-aware IsExpanded sync when a container is prepared → already present, aligned to upstream's form.
  • TreeViewItem.xaml: Foreground on the ContentPresenter → already present.
  • APITests/TreeViewTests.cs: SelectedItemsTest and helpers → TreeViewTests.mux.cs.
  • TestUI: partial selectors, container-reuse buttons of TreeViewItemsSourceTestPage (the page and TreeViewViewModel.cs are ported as a whole), perf scenario of TreeViewPage.

Not applicable

  • TreeView.vcxitems (*Perf2026 page types), static_cast<double> in UpdateIndentation, whitespace-only edits.
  • InteractionTests/TreeViewTests.cs (+39): Uno cannot run interaction tests yet.
  • [TestProperty("TestPass:MaxOSVer", …)] on VerifyVisualTree: the test is not ported, it needs VisualTreeTestHelper and its verification files.

Skipped: none, so there is no skipped-items issue.

Line-by-line review against 2.7.0

Upstream Uno Result
TreeView.cpp/.h/.idl TreeView.cs, .Properties.cs, .Events.cs, TreeViewSelectionMode.cs Gaps fixed: the five list control subscriptions are revoked when the template is reapplied (were plain +=); m_containerContentChangedSource is typed for ListViewBase (the handler cast its sender to TreeView). Marked: #15214 and #25796 handling, Equals in GetAssociatedNodeImpl
TreeViewList.cpp/.h TreeViewList.cs Matches. Marked: base prepare order, #15214, #25796, IsCustomReorder, IsGeneratedContainer, OnDropInternal, GetName for the protected GetNameCore
TreeViewItem.cpp/.h TreeViewItem.cs, .Properties.cs Gaps fixed: UpdateSelectionVisual checks the list control for null; the check box handlers are detached on re-template (stands in for the two revokers, no per-item allocation); the finalizer is gone. Marked: RecycleEvents detaches PointerPressed (upstream revokes PointerCanceled with that token), null check box guard
TreeViewNode.cpp/.h TreeViewNode.cs, .Properties.cs, .Events.cs, TreeViewNodeVector.cs, TreeNodeSelectionState.cs Gaps fixed: ToString() without content and ICustomPropertyProvider.Type use the runtime type's full name (checked on WinUI); InsertAt/ReplaceAll assert like upstream instead of throwing. Marked: RemoveAtEnd (upstream passes the flag as the index)
ViewModel.cpp/.h TreeViewViewModel.cs, .Events.cs, SelectedTreeNodeVector.cs, SelectedItemsVector.cs Gaps fixed: SelectedItems.Insert and its indexer go through InsertAt/SetAt and keep SelectedNodes in sync (checked on WinUI); the range and ItemChanged checks are asserts. Marked: selection pushed to the list without a container, pruning on reset, the enumerator (stands in for Implement_IIterator), GetMany/ReplaceAll (#if false, no IList<T> counterpart), the view model finalizer
TreeView*EventArgs.cpp/.h (6) same names Gap fixed: TreeViewDragItemsStartingEventArgs.Cancel forwards to the ListView arguments; it was an auto-property, so a drag could not be canceled
TreeViewItemTemplateSettings.* TreeViewItemTemplateSettings.cs Matches
TreeView*AutomationPeer.cpp/.h, TreeViewAutomationPeers.idl the three peers Match
TreeView.xaml, TreeViewItem.xaml, TreeView_themeresources.xaml FluentTheme copies Identical to 2.7.0, tracked as mirrors
APITests/TreeViewTests.cs (23 tests) TreeViewTests.mux.cs 22 present after this PR. Not ported: VerifyVisualTree (see above). Disabled: TreeViewInheritanceTest (disabled upstream too), TreeViewSelectionChangedMultipleMode (see below)
TestUI/* SamplesApp.Samples/.../TreeView Members and named elements match; Uno additions (GetFrame, GetItemsCount, the navigation grid) are marked

Not done here: the port keeps its monolithic files (no .mux.cs / .h.mux.cs split), and most public members of TreeViewNode, TreeViewItem and the event args have no XML docs.

Uno workarounds

Each one was switched off in turn and the TreeView runtime tests were rerun. Open parity questions were checked on native WinUI (WinAppSDK 2.5.1) with temporary probe tests, since *.mux.cs tests are not compiled on that head.

Location What it does Verdict Evidence
TreeViewItem.OnLoaded Re-applies indentation and selection visual Removed All TreeView tests pass without it. New When_MultiSelect_Recycled_Containers_Keep_Selection_And_Indentation passes without it and fails once the upstream path (OnContainerContentChanging) is disabled as well. The UI test its comment cited is itself ignored
TreeViewItem.OnApplyTemplate Re-applies the selection visual Removed Same
TreeViewItem.AncestorTreeView, TreeViewList.AncestorTreeView Finds the TreeView through the owning ItemsControl before the container is in the tree Removed Same
~TreeViewItem() Detached the chevron handler from the finalizer thread Removed Both objects are unreachable when it runs; it only delayed collection of every container
TreeViewList.PrepareContainerForItemOverride: base call first A recycled container still carries the previous item's state Kept When_SelectNode_DoesNotToggle_OtherNodesExpansion times out with upstream's order
#25796 stale selection (TryTakeStaleUnselection, IsPreparingStaleSelection, ChangeSelectedItem) Ignores a stale IsSelected from a two-way binding Kept 2 tests fail without it
#15214 pending SelectedItem Selects an item set before the template exists or under a collapsed node Kept 6 tests fail without it. WinUI loses that selection (nodes=0, container not selected), so this is a deliberate improvement
NotifyContainerOfSelectionChange: push to the list without a container Keeps TreeView.SelectedItem in step with a node that has no container Kept 4 tests fail without it. WinUI leaves SelectedItem null and the list index at −1
PruneDetachedSelectedNodes Drops selected nodes a source reset removed Kept WinUI keeps them (nodes=1 items=1, no event). Now covered by When_ItemsSource_Cleared_MultiSelect_Selection_Is_Dropped. The item-map half of this workaround is gone with the map
GetAssociatedNodeImpl: Equals Finds a node by value Kept, needs a decision WinUI compares identity: SelectedItem = 2 or an equal fresh string selects nothing there. Uno already matched by value through the old dictionary, so this keeps today's behavior
UpdateMultipleSelection: null check box Tolerates a template without MultiSelectCheckBox Kept No test needs it, but removing it turns a no-op into a crash for re-templated items
IsGeneratedContainer, IsCustomReorder ItemsControl and ListViewBase contracts Kept Read in ItemsControl.ClearContainerForItemOverride and ListViewBase.DragDrop; drag reorder is only covered by UI tests
~TreeViewViewModel() Stands in for the C++ destructor Kept One per TreeView; removing it would orphan ClearEventTokenVectors
TreeViewPage.xaml.cs: Bindings.Update Sets the value directly Unclear, kept Sample only, exercised by UI tests

Disabled tests: TreeViewSelectionChangedMultipleMode was re-enabled and still fails, for a reason outside this area: in SelectionMode.None, WinUI's ListView unselects the other containers when ListViewItem.IsSelected is set, Uno's keeps them. Its [Ignore] now says so.

Tests

  • Skia desktop, TreeView runtime tests (MUXControlsTestApp.TreeViewTests, both Given_TreeView classes): 54 passed, 2 skipped, 0 failed.
  • New: SelectedItemsTest, TreeViewBackgroundTest, VerifySettingSelectionDoesNotCrash (upstream), When_DragItemsStarting_Canceled_Drag_Does_Not_Start (fails without the fix), When_ItemsSource_Cleared_MultiSelect_Selection_Is_Dropped, When_MultiSelect_Recycled_Containers_Keep_Selection_And_Indentation.
  • Uno.UI and Uno.UI.RuntimeTests.Generic build in Release without UnoFastDevBuild.
  • detect.ps1 reports the area up to date; build/winui-sync/tests/run.ps1 passes.

PR Checklist ✅

🤖 Generated with Claude Code

https://claude.ai/code/session_01TXMNu2q9JbwVarbJ7PDuaT

MartinZikmund and others added 8 commits November 24, 2026 11:18
Ports the upstream changes since winui3/release/1.4.2 and closes the
gaps a line-by-line review against 2.7.0 found.

Upstream changes:
- SelectedNodes and SelectedItems look an item up from the position of
  the last hit (IndexOf_OptimizedForRemove), and descendants are
  unselected back to front, so unselecting a large subtree is no longer
  quadratic.
- The item to node map is gone, the node is found by walking the tree.

Review gaps:
- SelectedItems.Insert and its indexer keep SelectedNodes in sync.
- The list control events are revoked when the template is reapplied.
- Parameter checks that are asserts in WinUI no longer throw.
- TreeViewNode reports its full type name when it has no content.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Claude-Session: https://claude.ai/code/session_01TXMNu2q9JbwVarbJ7PDuaT
TreeViewDragItemsStartingEventArgs.Cancel was a plain property, so
setting it never reached the ListView arguments and the drag started
anyway. WinUI forwards it.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Claude-Session: https://claude.ai/code/session_01TXMNu2q9JbwVarbJ7PDuaT
The finalizer only detached the chevron handler, from the finalizer
thread. Both objects are unreachable by then, so it did nothing but keep
every container alive for one more collection.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Claude-Session: https://claude.ai/code/session_01TXMNu2q9JbwVarbJ7PDuaT
TreeViewItem re-applied its indentation and selection visual when it was
loaded and when its template was applied, and looked its TreeView up
through the owning ItemsControl while it was not in the visual tree yet.
They covered containers the native list views prepared before they were
attached. The WinUI path, TreeViewList.OnContainerContentChanging, is now
enough: the TreeView runtime tests pass without them, and a recycling
test only fails once that path is disabled as well.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Claude-Session: https://claude.ai/code/session_01TXMNu2q9JbwVarbJ7PDuaT
Every deviation from WinUI that stays after the audit says why it is
there. The reasons were checked against native WinUI and the runtime
tests: #15214 and #25796 handling, the base prepare order and the
selection pushed to the list each have tests failing without them.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Claude-Session: https://claude.ai/code/session_01TXMNu2q9JbwVarbJ7PDuaT
Ports SelectedItemsTest, TreeViewBackgroundTest and
VerifySettingSelectionDoesNotCrash, the TreeViewItemsSourceTestPage
sample and the perf scenario of TreeViewPage.

TreeViewSelectionChangedMultipleMode stays disabled, now with the actual
cause: a ListView in SelectionMode.None keeps the other items selected
when ListViewItem.IsSelected is set, WinUI unselects them.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Claude-Session: https://claude.ai/code/session_01TXMNu2q9JbwVarbJ7PDuaT
- Canceling DragItemsStarting keeps the drag from starting.
- Selected nodes removed by an ItemsSource reset leave the selection.
- Recycled containers keep their selection state and indentation in
  multi-select mode.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Claude-Session: https://claude.ai/code/session_01TXMNu2q9JbwVarbJ7PDuaT
Records TreeView at winui3/release/2.7.0. The three theme XAML files are
verbatim copies of upstream and are tracked as mirrors. The headers of
the area now name only their upstream files, the entry holds the
version; the ported tests and samples gain the header they lacked.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Claude-Session: https://claude.ai/code/session_01TXMNu2q9JbwVarbJ7PDuaT
@github-actions github-actions Bot added area/build Categorizes an issue or PR as relevant to build infrastructure area/automation Categorizes an issue or PR as relevant to project automation labels Nov 24, 2026
@github-actions

github-actions Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @MartinZikmund's task in 21s —— View job


PR review: TreeView onboarding to the WinUI port sync (2.7.0)

Verdict: ship after minor fixes. I found 0 high, 1 medium and 1 low severity issues. They are posted inline. I reviewed the diff by inspection only. I did not build or run any tests.

Cross-cutting notes

  • Test skipped: TreeViewSelectionChangedMultipleMode stays [Ignore]d. The cause is outside this area (ListView behavior in SelectionMode.None), and the PR documents it. Please make sure a tracking issue exists for it.
  • Equals decision: The "needs a decision" item on Equals versus identity in GetAssociatedNodeImpl is tied to the performance comment. Matching WinUI would also bring back O(1)-ish comparisons.
  • Not reviewed in depth: The PR touches ObservableVector<T> in Uno.Foundation. IndexOf is now virtual and a new IndexOf_OptimizedForRemove was added. This looks correct, but a tiny unit test for the wrap-around search would help.
  • Commits and workaround audit: The commit messages and the workaround audit look consistent with AGENTS.md.

@mergify

mergify Bot commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

Tick the box to add this pull request to the merge queue (same as @mergifyio queue). If it does not match the queue conditions yet, it enters the queue once it does.

  • Queue this pull request once it meets the queue conditions


internal TreeViewNode GetAssociatedNode(object item) => GetAssociatedNodeImpl(item, m_rootNode);

private TreeViewNode GetAssociatedNodeImpl(object item, TreeViewNode node)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Performance (medium): GetAssociatedNode is now an O(N) recursive walk with Equals on every call (the dictionary was O(1)). It's reached from TreeViewList (ItemFromNode/container prep paths, line ~769) and the view model, so on large expanded trees each container preparation or selection change can become O(N), i.e. O(N²) overall. Upstream accepts this, but upstream compares by identity (cheap), while Equals can call user overrides. Consider a short-circuit via ReferenceEquals first, and note the perf trade-off in the PR; the "needs a decision" item in the description should also weigh this cost.

Comment on lines +47 to +54
#if HAS_UNO
// TODO Uno: Original C++ destructor cleanup. Uno does not support cleanup via finalizers.
// Original destructor logic (not executed):
// ~TreeViewItem()
// {
// // We only need to use safe_get in the deconstruction loop
// RecycleEvents(true /* useSafeGet */);
// }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Style (low): This is a commented-out copy of the removed finalizer. AGENTS.md says comments should never narrate code removal/history; the finalizer is gone, so drop this block (the PR description already records why).


Assert.IsNotNull(checkBox, $"[{step}] {node.Content} has no selection check box");
Assert.AreEqual(expected, checkBox.IsChecked, $"[{step}] {node.Content} check box");
Assert.AreEqual(node.Depth * 16, container.TreeViewItemTemplateSettings.Indentation.Left, $"[{step}] {node.Content} indentation");
{
var nodeContent = treeView.SelectedNodes[i].Content as TreeViewItemSource;
Verify.IsNotNull(nodeContent);
Verify.AreEqual(expected[i], nodeContent.Content, $"Verify TreeView SelectedNodes[{i}]");
{
var selectedItem = treeView.SelectedItems[i] as TreeViewItemSource;
Verify.IsNotNull(selectedItem);
Verify.AreEqual(expected[i], selectedItem.Content, $"Verify TreeView SelectedItems[{i}]");
var treeViewList = FindVisualChildByName(treeView, "ListControl") as TreeViewList;

// Make sure the TreeViewList does not already have the background color we are using for this test.
bool testCondition = treeViewList.Background is SolidColorBrush brush && brush.Color == Colors.Green;
Comment on lines +485 to +493
if (node.Content is { } content)
{
// Uno specific: WinUI compares identities. A boxed value or a string is not the same instance in .NET,
// so items are compared with Equals.
if (Equals(content, item))
{
return node;
}
}
Comment on lines +60 to +67
if (_list.Count == 0)
{
startNextSearchAt = 0;
}
else
{
startNextSearchAt = _list.Count - 1;
}
Comment on lines +81 to +91
if (index > 0)
{
// Next time we search start near this index. We assume that the remove is being processed from the end
// of the vector towards index 0, so the next item being removed is probably at "index - 1". Start the
// next search there.
startNextSearchAt = index - 1;
}
else
{
startNextSearchAt = index;
}
Comment on lines +944 to +951
if (string.IsNullOrEmpty(prefix))
{
name = $"{i}";
}
else
{
name = $"{prefix}.{i}";
}
@unodevops

Copy link
Copy Markdown
Contributor

🤖 Your WebAssembly Sample App stage site is ready! Visit it here:

@nventive-devops

Copy link
Copy Markdown
Contributor

The build 248714 found UI Test snapshots differences: skia-linux-screenshots: 237, skia-windows-screenshots: 250

Details
  • skia-linux-screenshots: 237 changed over 2504

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • Accessibility_Showcase.png-dark
    • AnimatedVisualsTestbedPage.png
    • Basics.png-dark
    • Basics.png
    • Border_CornerRadius_Binding.png-dark
    • Border_CornerRadius_Binding.png
    • ComboBox_MaxDropdownHeight.png-dark
    • ComboBox_MaxDropdownHeight.png
    • AnimatedBackVisualSourceSamplePage.png-dark
    • AnimatedVisualsTestbedPage.png-dark
    • AutomationProperties_AutomationId.png
    • BasicAcrylicBrushTest2.png-dark
    • BasicAcrylicBrushTest2.png
    • Border_CornerRadius_BorderThickness.png-dark
    • Border_CornerRadius_BorderThickness.png
    • ClipboardTests.png-dark
    • CompositionNineGridBrush_Source_Changes.png-dark
    • CompositionNineGridBrush_Source_Changes.png
    • BenchmarkDotNet.png-dark
    • BenchmarkDotNet.png
  • skia-windows-screenshots: 250 changed over 2504

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • Accessibility_Showcase.png-dark
    • ButtonClippingTestsControl.png-dark
    • ButtonClippingTestsControl.png
    • CalendarView_Theming.png-dark
    • CalendarView_Theming.png
    • ColorPickerSample.png-dark
    • ColorPickerSample.png
    • AutomationProperties_AutomationId.png-dark
    • AnimatedVisualsTestbedPage.png-dark
    • AutomationProperties_StructureAndProps.png-dark
    • BasicAcrylicBrushTest.png-dark
    • BasicAcrylicBrushTest.png
    • BreadcrumbBarPage.png-dark
    • BreadcrumbBarPage.png
    • ComboBox_MaxDropdownHeight.png-dark
    • ComboBox_MaxDropdownHeight.png
    • BasicAcrylicBrushTest2.png-dark
    • BasicAcrylicBrushTest2.png
    • AnimatedBackVisualSourceSamplePage.png
    • AnimatedVisualsTestbedPage.png

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

Labels

area/automation Categorizes an issue or PR as relevant to project automation area/build Categorizes an issue or PR as relevant to build infrastructure

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants