Repository navigation
Description
Summary
Uno's classic Microsoft.UI.Xaml.Controls.ScrollViewer declares IScrollAnchorProvider but the implementation is stubbed:
ScrollViewer.CurrentAnchorreturnsnull(annotated[Uno.NotImplemented]).ScrollViewer.RegisterAnchorCandidate(UIElement)raisesTryRaiseNotImplemented.UIElement.CanBeScrollAnchorstores the value as a dependency property but theOnCanBeScrollAnchorChangedcallback that would register/unregister the element with the nearest anchor provider is commented out.
ItemsRepeater.ViewportManagerWithPlatformFeatures relies on this interface to maintain scroll position across layout changes — specifically during fast scrolling through content with high size variance, and when realized content grows in place. Without a working anchor provider, the correction mechanism described in #23042 cannot fully service shifts through the scroller and has to fall back to m_unshiftableShift absorption, which only partially masks the problem.
ScrollView / ScrollPresenter (the newer Microsoft.UI.Xaml.Controls primitives) already forward to ScrollPresenter.AnchorElement() properly — only the classic ScrollViewer is missing. Apps still commonly use ScrollViewer as the surrounding scroller (it is the control in template-generated content and shipped XAML samples), so the anchor pipeline needs to work there too.
Current behavior
src/Uno.UI/UI/Xaml/Controls/ScrollViewer/ScrollViewer.cs:642-645:
// Note for implementers: Search for SharedHelpers.IsRS5OrHigher() in ItemsRepeaterScrollHost.cs
// => This should be re-enabled AND this class also gives the base implementation for the anchoring
[global::Uno.NotImplemented]
public UIElement? CurrentAnchor => null;src/Uno.UI/Generated/3.0.0.0/Microsoft.UI.Xaml.Controls/ScrollViewer.cs:529-531 (generated stub):
public void RegisterAnchorCandidate(global::Microsoft.UI.Xaml.UIElement element)
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Microsoft.UI.Xaml.Controls.ScrollViewer", "void ScrollViewer.RegisterAnchorCandidate(UIElement element)");
}src/Uno.UI/UI/Xaml/UIElement.mux.cs:1325-1330, 1975-1980 (two callsites of OnCanBeScrollAnchorChanged are commented out):
// TODO Uno: Commented out to match winUI behavior
//if (CanBeScrollAnchor)
//{
// OnCanBeScrollAnchorChanged();
//}Downstream consumer:
src/Uno.UI/UI/Xaml/Controls/Repeater/ViewportManagerWithPlatformFeatures.cs:87-121—SuggestedAnchorasksm_scroller?.CurrentAnchoron every layout; alwaysnulltoday forScrollViewer.src/Uno.UI/UI/Xaml/Controls/Repeater/ViewportManagerWithPlatformFeatures.cs:293-303—OnElementPreparedsetselement.CanBeScrollAnchor = truebut becauseOnCanBeScrollAnchorChangedis a no-op andRegisterAnchorCandidatethrows, no actual candidate registration occurs.
Expected behavior
Classic ScrollViewer must implement IScrollAnchorProvider to full WinUI semantics, enabling:
- Candidate registration — elements marked
CanBeScrollAnchor = true(or explicitly registered viaRegisterAnchorCandidate) are tracked as potential anchors. - Anchor selection — on every arrange pass,
CurrentAnchorreturns the candidate whose bounds best match the anchor-picking algorithm, usingHorizontalAnchorRatioandVerticalAnchorRatio. - Anchor tracking across arrange — when arranging moves the anchor element's position within the scrollable content,
ScrollViewershifts itsHorizontalOffset/VerticalOffsetby the pre-vs-post delta so the anchor stays visually fixed in the viewport. This is the mechanism that absorbs them_expectedViewportShiftthatItemsRepeaterrequests.
Source to port from
Primary port source: WinUI DirectUI ScrollViewer itself — microsoft-ui-xaml2/src/dxaml/xcp/dxaml/lib/ScrollViewer_Partial.cpp (+ .h). This is the canonical C++ implementation of classic ScrollViewer with IScrollAnchorProvider fully built in. All the pieces we need are here:
Anchor provider API (these are the exact methods to port):
ScrollViewer::get_CurrentAnchorImpl(ScrollViewer_Partial.cpp:9345).ScrollViewer::RegisterAnchorCandidateImpl(:9373).ScrollViewer::UnregisterAnchorCandidateImpl(:9412).
Internal machinery used by the anchor provider:
ScrollViewer::EnsureAnchorElementSelection(:16444) — selects the best anchor from registered candidates based onHorizontalAnchorRatio/VerticalAnchorRatioand the current viewport, taking theAnchorRequestedevent into account.ScrollViewer::ResetAnchorElement(:16428) — clears the cached anchor and marksm_isAnchorElementDirty = true.ScrollViewer::ProcessAnchorCandidate(:16557) — given a candidate, tests validity and computes its viewport-anchor-point distance.ScrollViewer::IsElementValidAnchor(:16670) — candidate must be visible, in the live tree,CanBeScrollAnchor == true, intersecting the viewport.ScrollViewer::ComputeViewportAnchorPoint(:16270) — produces(horizontalOffset, verticalOffset)in viewport space based on anchor ratios.ScrollViewer::ComputeViewportToElementAnchorPointsDistance— invoked byArrangeOverrideboth pre- and post-arrange; the diff is the offset correction to apply.
Fields (ScrollViewer_Partial.h:2270-2277):
TrackerPtr<wfc::IVector<xaml::UIElement*>> m_anchorCandidates;
TrackerPtr<wfc::IVector<xaml::UIElement*>> m_anchorCandidatesForArgs;
bool m_isAnchorElementDirty{ true };
TrackerPtr<xaml::IUIElement> m_anchorElement;
wf::Rect m_anchorElementBounds{};
// Plus m_pendingViewportShiftX / m_pendingViewportShiftY, m_horizontalAnchorRatio / m_verticalAnchorRatioIntegration point — ScrollViewer::ArrangeOverride (ScrollViewer_Partial.cpp:~2140-2250):
// 1) Pre-arrange: compute viewport with pending shifts, pick anchor, snapshot its anchor-point distance.
get_ZoomedHorizontalOffsetWithPendingShifts(&preArrangeViewportX);
get_ZoomedVerticalOffsetWithPendingShifts(&preArrangeViewportY);
preArrangeViewport = { preArrangeViewportX, preArrangeViewportY, viewportWidth, viewportHeight };
if (isAnchoringElementHorizontally || isAnchoringElementVertically) {
EnsureAnchorElementSelection(preArrangeViewport);
ComputeViewportToElementAnchorPointsDistance(preArrangeViewport, /*isForPreArrange*/ true, &preArrangeDistance);
} else {
ResetAnchorElement();
}
// 2) Base arrange.
ScrollViewerGenerated::ArrangeOverride(finalSize, returnValue);
m_pendingViewportShiftX = 0.0;
m_pendingViewportShiftY = 0.0;
// 3) Post-arrange: re-compute distance, diff against pre, shift offsets by the delta.
if (!isnan(preArrangeDistance.Width) || !isnan(preArrangeDistance.Height)) {
ComputeViewportToElementAnchorPointsDistance(postArrangeViewport, /*isForPreArrange*/ false, &postArrangeDistance);
// ... apply delta via ChangeView / direct offset update, accumulate into m_pendingViewportShiftX/Y
}Note on ItemsRepeaterScrollHost (microsoft-ui-xaml2/src/controls/dev/Repeater/ItemsRepeaterScrollHost.cpp): this is an RS3 downlevel adapter that adds anchor-provider semantics to a ScrollViewer that doesn't have them natively. Since modern Windows (RS5+) ScrollViewer implements the anchor provider directly, ItemsRepeaterScrollHost is the wrong target. Keep it as a secondary reference — its TrackElement / GetAnchorElement are a simpler sketch of the same algorithm and may help cross-check — but port from ScrollViewer_Partial.cpp.
Secondary reference: ScrollPresenter::AnchorElement, RegisterAnchorCandidate, ProcessAnchorCandidate, ComputeViewportAnchorPoint, IsElementValidAnchor in microsoft-ui-xaml2/src/controls/dev/ScrollPresenter/ScrollPresenter.cpp. Uno already ports this — see src/Uno.UI/UI/Xaml/Controls/ScrollPresenter/ScrollPresenterPrivate.cs:92. Use as cross-check for behavioral parity.
Proposed approach
Port ScrollViewer_Partial.cpp's anchor pipeline onto Uno's ScrollViewer (as a partial — e.g. ScrollViewer.Anchoring.cs).
Fields (mirror ScrollViewer_Partial.h:2270-2277)
private readonly List<WeakReference<UIElement>> _anchorCandidates = new();
private List<UIElement>? _anchorCandidatesForArgs; // snapshot for AnchorRequested event args
private bool _isAnchorElementDirty = true;
private WeakReference<UIElement>? _anchorElement;
private Rect _anchorElementBounds;
private double _pendingViewportShiftX;
private double _pendingViewportShiftY;
private double _horizontalAnchorRatio = double.NaN; // matches WinUI default
private double _verticalAnchorRatio = double.NaN;Public API — IScrollAnchorProvider
Port verbatim from get_CurrentAnchorImpl / RegisterAnchorCandidateImpl / UnregisterAnchorCandidateImpl. Swap the TrackerPtr/ComPtr ceremony for .NET weak references; the control flow is identical.
Anchor selection — EnsureAnchorElementSelection
Port from ScrollViewer_Partial.cpp:16444 including:
- Early-out when
_isAnchorElementDirtyis false. - Honoring the
AnchorRequestedevent (WinUI raises it so apps can override selection; Uno can initially leave the event asNotImplementedbut the selection-via-candidates branch must work). - Walking
_anchorCandidates, callingProcessAnchorCandidateto compute per-candidate viewport-anchor-point distance. - Picking the minimum-distance candidate that passes
IsElementValidAnchor.
Validation — IsElementValidAnchor
Port from ScrollViewer_Partial.cpp:16670-16730. The element must: be connected (visual parent chain leads to the ScrollContentPresenter content), be visible, have CanBeScrollAnchor == true, have non-empty intersection with the viewport.
Geometry — ComputeViewportAnchorPoint + ComputeViewportToElementAnchorPointsDistance
ComputeViewportAnchorPoint(viewport, ratios) → point: returns the viewport-space point corresponding to(viewport.X + ratioX * viewport.Width, viewport.Y + ratioY * viewport.Height).ComputeViewportToElementAnchorPointsDistance(viewport, isForPreArrange) → Size: returns(viewportAnchorPoint - elementAnchorPoint)where the element's anchor point iselementBounds.Origin + ratios * elementBounds.Size. Cache theelementBoundsper-candidate during pre-arrange and reuse during post-arrange so anchor drift reflects real layout motion.
ArrangeOverride integration
Intercept Uno's ScrollViewer.ArrangeOverride (already a partial). Sequence per ScrollViewer_Partial.cpp:2140-2250:
- Compute
preArrangeViewportincluding_pendingViewportShiftX/Y. - If
_horizontalAnchorRatioor_verticalAnchorRatioare notNaN(or any candidate opted in), callEnsureAnchorElementSelection(preArrangeViewport)andComputeViewportToElementAnchorPointsDistance(pre, isForPreArrange: true). - Call base arrange.
- Reset
_pendingViewportShiftX = _pendingViewportShiftY = 0. - Recompute post-arrange viewport + distance.
- The delta between pre and post is the anchor drift; issue a non-animated
ChangeView(or equivalent internal offset update) by that delta. Accumulate into_pendingViewportShiftX/Yso the next arrange pass sees the in-flight offset.
UIElement wiring
Restore UIElement.OnCanBeScrollAnchorChanged at UIElement.mux.cs:1328, 1977. On true: walk up via VisualTreeHelper to the nearest ancestor implementing IScrollAnchorProvider and RegisterAnchorCandidate. On false: UnregisterAnchorCandidate. Also unregister on Unloaded and on ancestor-change. WinUI tracks this on CUIElement; the mechanism we need in Uno is equivalent — ensure parent-change unregisters from the previous provider and registers with the new one.
Opt-out / default-off
Only activate the anchoring path when at least one candidate is registered (same as WinUI — m_anchorCandidates empty == no anchor work). Prevents regressions on simple ScrollViewer usage that relies on offset not silently shifting during arrange.
Platform scope
- Phase 1: Skia targets (Desktop, WebAssembly, Skia Android/iOS). The managed
ScrollContentPresenter/ScrollViewerpath allows synchronous offset correction during arrange. - Phase 2 (follow-up issue): Native-backed platforms (native iOS/Android
ScrollViewer). Native scroll views apply offset asynchronously; the pre/post-arrange diff may need to be applied in a dispatcher callback and may needShouldReportNegativeOffsetsor equivalent allowances. Document explicitly.
Acceptance criteria
ScrollViewer.CurrentAnchorreturns a non-null element when the ScrollViewer has registered candidates intersecting the viewport; matchesget_CurrentAnchorImplbehavior on equivalent input.ScrollViewer.RegisterAnchorCandidate/UnregisterAnchorCandidatemaintain the candidate list; weak references allow elements to be GC'd.UIElement.CanBeScrollAnchor = truecauses auto-registration with the nearest ancestorIScrollAnchorProvider.- Runtime test
When_RealizedItemGrows_Then_VisibleAnchorStable(from test: Add runtime tests for ItemsRepeater fast-scroll and scroll-to-top with high-variance item heights #23041) passes on Skia Desktop and WebAssembly. - Removing the
Math.Max(0, firstRealizedMajor)clamp (see fix: StackLayout.GetExtent clamps extent origin to 0, breaking ItemsRepeater's negative-offset correction #23042) does not regressWhen_ItemSignificantlyTaller_Then_VirtualizeProperly. HorizontalAnchorRatio/VerticalAnchorRatioDPs round-trip and affect selection per WinUI.- No regression in the existing scrolling runtime tests.
Risks
- Anchor tracking firing during user scroll can fight the user.
ScrollViewer_Partial.cpp'sResetAnchorElement/m_isAnchorElementDirtyhandling duringViewChangingis the reference; port verbatim. - Many apps rely on
ScrollViewernot silently changing its offset during arrange. Mitigation: default-off — the anchor path only runs when a candidate is explicitly registered. - Native-backed ScrollViewer paths cannot be covered in Phase 1; document explicitly.
Related
- test: Add runtime tests for ItemsRepeater fast-scroll and scroll-to-top with high-variance item heights #23041 (runtime tests exercise this code path).
- fix: StackLayout.GetExtent clamps extent origin to 0, breaking ItemsRepeater's negative-offset correction #23042 (
fix: StackLayout.GetExtent clamps extent origin to 0) is the companion fix — the clamp exists today partly because the anchor provider is not wired up. - chore: Resync ItemsRepeater / StackLayout / FlowLayoutAlgorithm / ViewportManagerWithPlatformFeatures from WinUI #23044 (
chore: Resync ItemsRepeater from WinUI) is the follow-up cleanup once this is in place.
References
- Uno gaps:
src/Uno.UI/UI/Xaml/Controls/ScrollViewer/ScrollViewer.cs:642-645;src/Uno.UI/Generated/3.0.0.0/Microsoft.UI.Xaml.Controls/ScrollViewer.cs:529-531;src/Uno.UI/UI/Xaml/UIElement.mux.cs:1325-1330, 1975-1980. - Existing Uno ports:
src/Uno.UI/UI/Xaml/Controls/ScrollView/ScrollView.cs:63-141;src/Uno.UI/UI/Xaml/Controls/ScrollPresenter/ScrollPresenterPrivate.cs:92;src/Uno.UI/UI/Xaml/Controls/Repeater/ItemsRepeaterScrollHost.cs. - Primary port source:
microsoft-ui-xaml2/src/dxaml/xcp/dxaml/lib/ScrollViewer_Partial.cpp(+.h). Key method line numbers (.cpp):2140(ArrangeOverride anchoring),9345(get_CurrentAnchorImpl),9373(RegisterAnchorCandidateImpl),9412(UnregisterAnchorCandidateImpl),16270(ComputeViewportAnchorPoint),16428(ResetAnchorElement),16444(EnsureAnchorElementSelection),16557(ProcessAnchorCandidate),16670(IsElementValidAnchor). Field declarations:.h:2270-2277. - Secondary reference:
microsoft-ui-xaml2/src/controls/dev/ScrollPresenter/ScrollPresenter.cpp. - Tertiary (RS3 downlevel shape, for cross-check only):
microsoft-ui-xaml2/src/controls/dev/Repeater/ItemsRepeaterScrollHost.cpp.
Activity
feat(scrollviewer): Implement CurrentAnchor and scroll anchoring
feat(scrollviewer): Implement CurrentAnchor and scroll anchoring