Skip to content

fix: Refresh NavigationView ancestor selection - #24509

Open
YoungSx wants to merge 4 commits into
unoplatform:masterfrom
YoungSx:fix/navigationview-selected-ancestors
Open

YoungSx wants to merge 4 commits into
unoplatform:masterfrom
YoungSx:fix/navigationview-selected-ancestors

Conversation

@YoungSx

@YoungSx YoungSx commented Sep 12, 2026 •

Copy link
Copy Markdown

GitHub Issue: closes #24508

PR Type:

🐞 Bugfix

What changed? 🚀

Moving a selected child between ObservableCollection groups can leave its former ancestors marked IsChildSelected. Collapsing an unrelated former parent then takes the selection indicator even though SelectedItem still identifies the moved leaf.

This Uno-specific correction tracks actual ancestor containers instead of resolving a stale previous index path after collection changes. It clears state on recycling/deselection, projects it for prepared containers, preserves ancestor identity on index-only changes, and excludes the selected leaf itself. Ancestor entries are removed before invoking dependency-property callbacks so synchronous changes cannot invalidate enumeration.

Follow-up 415d7c7 addresses the requested changes: after refreshing ancestors, the outer selection callback stops if a synchronous property callback superseded its captured selection. Real runtime coverage includes both a root fallback and a nested fallback chosen by that callback.

Validation

Code review: reviewed ownership, reentrancy, API contracts, security, performance, operability and test quality through the repository's eight-lens panel. The current guard uses final selected-item identity, matching the helper's contract; this is not a claim of generation-level intent tracking.

Compile: full source SamplesApp Release/net10.0-desktop built on Linux ARM64 with .NET SDK 10.0.400. Local analyzers were disabled using UnoFastDevBuild. The final build succeeded; existing MSB4011 duplicate-import warnings appear during initial project evaluation even though the build summary reports zero warnings. The previous nullable automation-provider conversion in this PR's runtime test was fixed with a provider-presence assertion.

Runtime: four methods / six parameterized executions from NavigationViewTests.AncestorSelection.cs passed twice on the real Skia X11 control tree, with zero failures, skips or retries. Coverage: data-bound reparenting; a collapsed destination; three-level index shifts with/without a pane-mode transition; clearing selection; synchronous ancestor-callback reselection to root and nested fallback items.

The compact-mode fixture respects native leaf auto-close: it reopens the pane before reselecting an explicit nested item and before checking its realized ancestor containers. Selected identity and the top-level ancestor are checked before that second reopening. All original ancestor assertions remain. This is not coverage of selecting a detached descendant with the pane kept closed.

Negative control: removing the five-line outer callback guard makes both new fallback rows fail at the retained-selection assertion. Restoring it makes both pass. Earlier development comparisons at Uno 6.7.103 also reproduced the original application indicator defect with the published assembly and passed with the equivalent source fix; those comparisons are not published-package validation.

Reproduction:

dotnet build src/SamplesApp/SamplesApp/SamplesApp.csproj -c Release -f net10.0-desktop -p:UnoFastDevBuild=true -p:UnoTargetFrameworkOverride=net10.0-desktop -p:UseSharedCompilation=false -m:1 -nr:false
# Base64-encode the fully-qualified method filter as required by the runtime-tests skill.
export UITEST_RUNTIME_TESTS_FILTER=$(printf %s Microsoft.UI.Xaml.Tests.MUXControls.ApiTests.NavigationViewTests.When_AncestorDeselectionCallbackSelectsFallback_NewSelectionIsPreserved | base64 -w0)
cd src/SamplesApp/SamplesApp/bin/Release/net10.0-desktop
xvfb-run -a dotnet SamplesApp.dll --runtime-tests=results.xml

Evidence on the validation host: /tmp/pr24509-final3/results.xml, /tmp/pr24509-repeat/results.xml, /tmp/pr24509-negative/results.xml, /tmp/pr24509-final3-build.log. The build process alone used a 3 GiB GC heap cap, workstation GC and GCConserveMemory=9 to limit host pressure; these settings did not change source or the test app's runtime configuration.

Pending: maintainer re-review, official upstream runtime/strict CI, and native WinUI behavioral parity. The MUX tests are excluded by the Windows runtime project, so its ordinary job must not be counted as execution of these cases. The Microsoft implementation still uses the old index-path algorithm: this change is intentionally Uno-specific, not a literal port.

Consumers must wait for a published package containing the fix. The downstream application PR salmonloop/salmon-egg#214 remains Draft and must not substitute a development DLL or disable its failing GUI gate to appear green.

PR Checklist ✅

  • 🧪 Added Runtime tests for the bug and adjacent lifecycle cases.
  • 📚 Docs have been added/updated following the documentation template (no public API changes).
  • 🖼️ Validated PR Screenshots Compare Test Run results.
  • ❗ Contains NO breaking changes.
  • 👀 Reviewed 2 other open pull requests (optional).

@morning4coffe-dev morning4coffe-dev left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The ancestor-identity approach addresses the stale-index-path problem, but the new early ancestor refresh creates a reentrancy boundary that the outer selection callback does not protect.

I exercised the exact selected methods with minimal container/selection-model stand-ins. When clearing the model selection resets an old ancestor's IsChildSelected, a synchronous property callback can select a fallback item. UpdateIsChildSelected notices the model change and returns, but OnSelectionModelSelectionChanged then continues with its previously captured null selectedItem and clears that fallback. The trace is ancestor callback selects Fallback -> SelectedItem=Fallback -> SelectedItem=null. A diagnostic post-refresh selection guard preserves the fallback.

The concrete SelectionModel raises SelectionChanged synchronously, and IsChildSelected is a public dependency property, so this is a reachable callback boundary rather than only a list-enumerator concern. Please protect the caller against the superseding selection and add a runtime case covering that fallback/reselection path.

WinUI source note: the pinned Microsoft implementation (d0c6705ec46d, controls/dev/NavigationView/NavigationView.cpp) still uses the previous-index-path approach and has no new ancestor refresh before this callback's ignore/selection checks. This is an intentional Uno-specific algorithm change, not a literal port; native behavioral parity should remain explicitly pending as the PR already states.

Evidence scope: exact-method execution with stand-ins and source tracing, not a full XAML/native WinUI runtime reproduction.

@morning4coffe-dev

Copy link
Copy Markdown
Member

/azp run

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines successfully started running 1 pipeline(s).

@morning4coffe-dev morning4coffe-dev left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Re-reviewed 415d7c743ccc999cc62cd2cfc9b8eab090340d9d against my previous e8f70b7 review and the complete three-file feature delta. Revalidating the captured item after the synchronous ancestor callbacks fixes the reported ownership boundary: the outer callback no longer applies its stale selection over the replacement, and the selected index is read after that revalidation.

I independently built the source SamplesApp in Release/net11.0-desktop and ran all six ancestor-selection cases twice on the real Skia Win32 control tree; all passed without skips or retries. A reviewer-only copy removing just the five-line outer guard made both root/nested fallback rows fail at the retained-selection assertion. Recompiling the original reviewed source restored all six passes. The provider-presence assertion and explicit compact-pane reopening were also reviewed; this does not claim coverage of detached-child selection while the pane remains closed.

Local builds used UnoFastDevBuild, not strict analyzer coverage; initial project evaluation still emitted the existing MSB4011 duplicate-import warnings. Native WinUI behavioral parity and the full upstream matrix remain pending. I requested the missing ordinary CI, and build 233542 is now running with this exact head verified as a merge parent. This is not a claim that CI has passed.

My reported reentrancy issue is fixed in this head. Approving the revision; normal independent-review and CI merge gates still apply.

@unodevops

Copy link
Copy Markdown
Contributor

@nventive-devops

Copy link
Copy Markdown
Contributor

The build 233542 found UI Test snapshots differences: skia-linux-screenshots: 57, skia-windows-screenshots: 2310, wasm: 11

Details
  • skia-linux-screenshots: 57 changed over 2348

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • CalendarView_Theming.png-dark
    • CalendarView_Theming.png
    • ButtonClippingTestsControl.png-dark
    • ButtonClippingTestsControl.png
    • Buttons.png-dark
    • Buttons.png
    • ClipboardTests.png-dark
    • DisplayInformation.png-dark
    • ElementLevelTheme.png-dark
    • ElementLevelTheme.png
    • ContextRequested.png-dark
    • ContextRequested.png
    • Focus_FocusVisual_Properties.png-dark
    • Gamepad_CurrentReading.png-dark
    • Gamepad_CurrentReading.png
    • Gamepad_Enumeration.png-dark
    • Gamepad_Enumeration.png
    • DropDownButtonPage.png-dark
    • DropDownButtonPage.png
    • Examples.png-dark
  • skia-windows-screenshots: 2310 changed over 2408

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • AppBar_KeyBoard.png-dark
    • AndroidWindowInsets.png
    • AnimatedIconPage.png
    • ApplicationViewSpanningRectsPage.png
    • AppBarButtonWithIconTest.png-dark
    • AppBarToggleButtonTest.png-dark
    • AppWindowTitleBar Properties.png-dark
    • ApplicationViewMode.png-dark
    • ApplicationViewSizing.png
    • Arrange_Performance01.png
    • AppWindowClosing.png
    • AppWindowFeatures.png
    • Attributed_text_Simple.png
    • AppWindowPresenters.png-dark
    • AppXamlDefinedResources.png-dark
    • AutoBorderStretchwithbottommargin.png
    • ArcSegment.png
    • Attributed_text_Simple.png-dark
    • AutomationPropertiesExtensions_Role.png
    • AuthenticationBroker_Demo.png
  • wasm: 11 changed over 1076

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • UITests.Microsoft_UI_Xaml_Controls.WebView2Tests.WebView2_NavigationProperties
    • UITests.Shared.Windows_UI_Xaml_Controls.MediaPlayerElement.MediaPlayerElement_Minimal
    • UITests.Shared.Windows_UI_Xaml_Controls.MediaPlayerElement.MediaPlayerElement_Ogg_Extension
    • SamplesApp.Windows_UI_Xaml_Controls.ListView.ListViewSelectedItems
    • SamplesApp.Wasm.Windows_UI_Xaml_Controls.ListView.ListView_IsSelected
    • UITests.Shared.Microsoft_UI_Xaml_Controls.ExpanderTests.WinUIExpanderPage
    • SamplesApp.Microsoft_UI_Xaml_Controls.WebView2Tests.WebView2_EnableDevTools
    • UITests.Windows_UI_Xaml_Controls.CalendarView.CalendarView_Theming
    • UITests.Uno_Web.Http.CookieManagerTests
    • Uno.UI.Samples.Content.UITests.WebView.WebView_AnchorNavigation
    • UITests.Windows_UI_Xaml_Media_Animation.ColorAnimation_Background

@mergify

mergify Bot commented Sep 14, 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

@morning4coffe-dev

morning4coffe-dev commented Sep 14, 2026 •

Copy link
Copy Markdown
Member

CI follow-up for 415d7c743ccc999cc62cd2cfc9b8eab090340d9d:

The initial iOS shard's only listed failure was Given_InputPane.When_Focused_Element_Not_Occluded_Then_Centered_Content_Is_Not_Moved. The exact base 06690db8 reproduces the same failure in build 233431's first attempt (test run 3942304); its targeted one-test retry passed (run 3942331). This is baseline-reproduced intermittent behavior, not new evidence against the ancestor-selection fix. I am not calling the whole base suite green.

The screenshot notice also needs its comparison scope kept clear: the comparer log used builds 211834 (May 10) and 212586 (May 14) as baselines, not the PR's exact base. Its 2,310 Windows differences therefore are not an isolated PR-versus-base regression count; this does not establish pixel parity either.

Update: build 233542 has now completed successfully for this exact head, and the required checks are passing. Keeping the source approval unchanged; independent approval is still required before merging. No check or queue bypass has been applied.

@MartinZikmund

Copy link
Copy Markdown
Member

@YoungSx This control is fully ported from WinUI, so Uno-specific changes should only be done in case there is an upstream bug in the WinUI control itself (and it should then also be reported on WinUI repository). Can you please check whether this issue is also happening on WinAppSDK? If not, then we must have some other issue in our ported sources.

@morning4coffe-dev

Copy link
Copy Markdown
Member

@MartinZikmund @YoungSx I checked this against native Windows App SDK 2.4.0/.NET 10, with no Uno control implementation loaded. The original stale-ancestor problem does reproduce upstream.

I compiled the unchanged six-case fixture from 415d7c74 into a standalone native app, supplying only native host/load/idle helpers and the test metadata marker. In two fresh runs, with 250 ms and then 750 ms idle barriers:

  • Moving the selected leaf between expanded parents, or into a collapsed destination, reaches the retained-selection assertion successfully but fails because the former source container still has IsChildSelected=true.
  • Inserting a root before the ancestor and then selecting a top-level item leaves the original parent marked child-selected, in both normal and compact-pane variants.
  • The two fallback-callback rows stop earlier: native never clears the old ancestor, so the callback count is 0, not 1. Those rows do not establish native behavior for the later reentrancy boundary fixed in the PR.

That is four repeatable original-bug scenarios after their initial selection/ancestor positive controls. The separately inspected upstream source at 439bda9 still resolves cleanup through the previous index path; I am not claiming that checkout is the exact source commit of the packaged runtime.

This provides native repro evidence for an upstream report. Please file/link that report as requested before settling the Uno-specific implementation. It is not a claim of complete algorithm parity or mobile coverage, and I have not opened an upstream issue or bypassed the remaining merge gates.

@YoungSx

YoungSx commented Sep 17, 2026

Copy link
Copy Markdown
Author

@MartinZikmund @morning4coffe-dev Thanks for investigating and verifying this against native Windows App SDK!

As requested, I have filed the upstream issue in the WinUI repository with the repro details:
microsoft/microsoft-ui-xaml#11927

Given that this is confirmed to be an upstream WinUI defect and the Uno-specific fix plus regression tests in this PR have been verified and approved, could you please advise if any further steps are needed, or proceed with the independent review for merging? Thank you!

@YoungSx

YoungSx commented Sep 24, 2026

Copy link
Copy Markdown
Author

@MartinZikmund @morning4coffe-dev Friendly follow-up. Since we have now confirmed the stale-ancestor defect reproduces on native Windows App SDK 2.4.0 and filed the upstream WinUI issue (microsoft/microsoft-ui-xaml#11927), would you be open to merging this Uno-side fix as an interim workaround, gated so it can be cleanly reverted once WinUI ships the upstream fix?

The change is scoped to refreshing NavigationView ancestor selection and is covered by the new root-level and nested fallback regression tests (the two added cases fail when the fix is removed). It has been APPROVED and the six-case Skia/X11 fixture passed two consecutive rounds with no retries or skips.

Happy to add a code comment linking #11927 with a removal condition, or adjust the gating if that helps. Thanks for your time!

@MartinZikmund

Copy link
Copy Markdown
Member

@YoungSx one last change please - it is our convention that when a part of the code is uno specific (in this case it is, at least until upstream also makes this change), we wrap it in #if HAS_UNO ... #endif and include a comment explaining what it relates to and ideally also link to the issue. Once this is in, we will merge the PR 👍

@YoungSx

YoungSx commented Oct 13, 2026

Copy link
Copy Markdown
Author

@MartinZikmund Done! I have wrapped all Uno-specific changes in #if HAS_UNO ... #endif with comments linking to microsoft/microsoft-ui-xaml#11927 and #24508, preserving the upstream WinUI baseline under #else. Ready for merge 👍

@MartinZikmund

Copy link
Copy Markdown
Member

/azp run

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines successfully started running 1 pipeline(s).

@unodevops

Copy link
Copy Markdown
Contributor

@nventive-devops

Copy link
Copy Markdown
Contributor

The build 239265 found UI Test snapshots differences: skia-linux-screenshots: 118, skia-windows-screenshots: 2458

Details
  • skia-linux-screenshots: 118 changed over 2458

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • ButtonClippingTestsControl.png-dark
    • ButtonClippingTestsControl.png
    • CalendarView_Theming.png-dark
    • CalendarView_Theming.png
    • Buttons.png-dark
    • Buttons.png
    • ClipboardTests.png-dark
    • CompositionEffectBrush.png-dark
    • CompositionEffectBrush.png
    • CompositionNineGridBrush_Source_Changes.png-dark
    • CompositionNineGridBrush_Source_Changes.png
    • ElementLevelTheme.png-dark
    • ElementLevelTheme.png
    • DisplayInformation.png-dark
    • DoubleImageBrushInList.png-dark
    • DoubleImageBrushInList.png
    • ImageBrushInList.png-dark
    • ImageBrushInList.png
    • DropDownButtonPage.png-dark
    • ImageBrushAlignmentXY.png-dark
  • skia-windows-screenshots: 2458 changed over 2488

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • AnimatedIconPage.png-dark
    • AnimatedVisualsTestbedPage.png-dark
    • ApplicationViewSizing.png-dark
    • AppWindowClosing.png-dark
    • AppWindowPresenters.png-dark
    • Arrange_Performance01.png-dark
    • Attributed_text_Supserscript.png
    • AutoBorderStretchwithleftmargin.png-dark
    • AutomationProperties_AutomationId.png
    • AutomationProperties_Landmark.png-dark
    • AutoSuggestBox_BitmapIcon.png-dark
    • AutoSuggestBox_BitmapIcon.png
    • BackGesture.png-dark
    • BackGesture.png
    • Basics_Automated.png-dark
    • Basics_Automated.png
    • BezierSegment.png-dark
    • BezierSegment.png
    • BitmapImage_vs_SvgImageSource.png-dark
    • BitmapImage_vs_SvgImageSource.png

@unodevops

Copy link
Copy Markdown
Contributor

⚠️⚠️ The build 239265 has failed on Uno.UI - CI.

Track selected ancestor containers across collection mutation instead of resolving the obsolete selected index path. Restore ancestor state when containers are prepared and clear it when they are recycled or selection is removed.

Add runtime coverage for reparenting, collapsed destinations, three-level index changes and pane-mode rebinding. The equivalent patch builds on the 6.7.103 source and passes a Skia X11 development navigation gate; master runtime CI remains required.
Wait for the destination repeater to realize the moved row before selecting it. Preserve the selected-container assertion and add the runtime-test namespace imports and issue trace metadata.

An isolated Skia X11 fixture passed the same reparenting sequence with expanded and collapsed destinations, three-level index changes, pane-mode rebind, null selection and synchronous selection callbacks.
Stop the outer selection callback when ancestor dependency-property callbacks supersede its captured selection. Cover root and nested fallback selection with real runtime tests.

Restore the compact pane visible hierarchy before testing nested ancestor flags, preserving native leaf auto-close behavior. Assert the expansion provider before invoking it.

Validation: full source-built SamplesApp, six Skia X11 runtime cases passed twice without retries; both fallback cases fail when the guard is removed. Existing MSB4011 duplicate-import warnings remain.
@YoungSx
YoungSx force-pushed the fix/navigationview-selected-ancestors branch from 88a702d to 3b91fd8 Compare October 14, 2026 06:23
@YoungSx

YoungSx commented Oct 14, 2026 •

Copy link
Copy Markdown
Author

Rebased onto latest master and aligned the runtime test with the new MUX test structure (NavigationViewTests.AncestorSelection.mux.cs), resolving the MSTEST0030 failure under the WinAppSDK build configuration.

@YoungSx

YoungSx commented Oct 14, 2026

Copy link
Copy Markdown
Author

/azp run

@azure-pipelines

Copy link
Copy Markdown
Commenter does not have sufficient privileges for PR 24509 in repo unoplatform/uno

@MartinZikmund MartinZikmund left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@YoungSx thanks for the #if HAS_UNO wrapping, and for filing microsoft/microsoft-ui-xaml#11927. The structure is what we wanted. Sorry to come back once more, but while going through the final diff I found one regression I can't merge as-is:

  1. Value-type menu items stop selecting on click. The new reentrancy guards compare items by reference (selectedItem != selectionModel.SelectedItem). SelectionModel.SelectedItem re-reads the item through ItemsSourceView.GetAt on every call, so for value-type items (e.g. MenuItemsSource = Enum.GetValues<Page>() or an ObservableCollection<int>) every read returns a freshly boxed object and the comparison is always true. See the inline comment for the exact path. A bare return there means a click never updates SelectedItem and never raises SelectionChanged.

Optional, not blocking:

  • The selected top-level item now always reports IsChildSelected == false. WinUI sets it to true for a size-2 path in UpdateIsChildSelectedForIndexPath (and the existing test asserts topLevel.IsChildSelected == false). That matches the intent of WinUI's own comment ("with the exception of the actual container"), so I'm fine keeping it. A short note in the HAS_UNO comment would help, so the next WinUI sync doesn't treat it as accidental drift.
  • UpdateIsChildSelectedForContainer runs on every ElementPrepared and walks the visual tree in GetIndexPathForContainer (and allocates) even when nothing is selected. An early out when selectedPath is null || selectedPath.GetSize() <= 2 (just clear the flag if set) avoids that cost on the common path.

Also, CI hasn't run on the rebased head yet. I'll kick it off once the fix is in.

// An index-only change preserves ancestor identities and may precede repeater index updates.
UpdateIsChildSelected(selectionModel.SelectedIndex);
// Ancestor property callbacks may supersede this selection synchronously.
if (selectedItem != selectionModel.SelectedItem)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This (and the same check in UpdateIsChildSelected / UpdateIsChildSelectedForIndexPath) uses reference equality. SelectionModel.SelectedItem goes through SelectedItems[0], which calls ItemsSourceView.GetAt -> ListAdapter.GenericList<object> -> IList.this[], so for value-type items each read is a new box.

Click path for a flat enum/int menu: OnNavigationViewItemIsSelectedPropertyChanged -> UpdateSelectionModelSelection -> SelectAt -> here. selectedItem != SelectedItem is true (nothing selected yet), we refresh ancestors (a no-op for a top-level item), then this check compares two different boxes and returns. SetSelectedItemAndExpectItemInvokeWhenSelectionChangedIfNotInvokedFromAPI is never reached, so SelectedItem stays unchanged and SelectionChanged doesn't fire. On master this works, because the existing selectedItem == SelectedItem check only skips the ignore, it never bails out.

Using object.Equals(...) in the three guards would fix this. A more robust option is a small selection counter: increment it at the top of OnSelectionModelSelectionChanged, capture it, and bail out if it changed after the ancestor refresh. Then the guard detects "a nested selection happened" without depending on item identity. Could you also add a runtime case with value-type items (e.g. MenuItemsSource = new ObservableCollection<int> { 1, 2 }, select via the container / automation peer, assert SelectedItem and that SelectionChanged fired)?

private void UpdateIsChildSelectedForContainer(NavigationViewItem container)
{
var selectedPath = m_selectionModel.SelectedIndex;
var containerPath = GetIndexPathForContainer(container);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Optional: this runs for every prepared container. GetIndexPathForContainer walks the visual tree and allocates a List<int> + IndexPath even when there is no selection or the selection is top-level (where no container can be an ancestor). Bailing out early when m_selectionModel.SelectedIndex is null or has size <= 2 (clearing IsChildSelected if it's set) keeps the virtualization path cheap.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

NavigationView retains selected ancestors after child reparenting

5 participants