Skip to content

feat: Implement IScrollAnchorProvider on classic ScrollViewer (CurrentAnchor, RegisterAnchorCandidate, anchor-tracking across layout) #23043

Description

@MartinZikmund

Summary

Uno's classic Microsoft.UI.Xaml.Controls.ScrollViewer declares IScrollAnchorProvider but the implementation is stubbed:

  • ScrollViewer.CurrentAnchor returns null (annotated [Uno.NotImplemented]).
  • ScrollViewer.RegisterAnchorCandidate(UIElement) raises TryRaiseNotImplemented.
  • UIElement.CanBeScrollAnchor stores the value as a dependency property but the OnCanBeScrollAnchorChanged callback 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 — SuggestedAnchor asks m_scroller?.CurrentAnchor on every layout; always null today for ScrollViewer.
  • src/Uno.UI/UI/Xaml/Controls/Repeater/ViewportManagerWithPlatformFeatures.cs:293-303 — OnElementPrepared sets element.CanBeScrollAnchor = true but because OnCanBeScrollAnchorChanged is a no-op and RegisterAnchorCandidate throws, no actual candidate registration occurs.

Expected behavior

Classic ScrollViewer must implement IScrollAnchorProvider to full WinUI semantics, enabling:

  1. Candidate registration — elements marked CanBeScrollAnchor = true (or explicitly registered via RegisterAnchorCandidate) are tracked as potential anchors.
  2. Anchor selection — on every arrange pass, CurrentAnchor returns the candidate whose bounds best match the anchor-picking algorithm, using HorizontalAnchorRatio and VerticalAnchorRatio.
  3. Anchor tracking across arrange — when arranging moves the anchor element's position within the scrollable content, ScrollViewer shifts its HorizontalOffset / VerticalOffset by the pre-vs-post delta so the anchor stays visually fixed in the viewport. This is the mechanism that absorbs the m_expectedViewportShift that ItemsRepeater requests.

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 on HorizontalAnchorRatio / VerticalAnchorRatio and the current viewport, taking the AnchorRequested event into account.
  • ScrollViewer::ResetAnchorElement (:16428) — clears the cached anchor and marks m_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 by ArrangeOverride both 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_verticalAnchorRatio

Integration 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 _isAnchorElementDirty is false.
  • Honoring the AnchorRequested event (WinUI raises it so apps can override selection; Uno can initially leave the event as NotImplemented but the selection-via-candidates branch must work).
  • Walking _anchorCandidates, calling ProcessAnchorCandidate to 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 is elementBounds.Origin + ratios * elementBounds.Size. Cache the elementBounds per-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:

  1. Compute preArrangeViewport including _pendingViewportShiftX/Y.
  2. If _horizontalAnchorRatio or _verticalAnchorRatio are not NaN (or any candidate opted in), call EnsureAnchorElementSelection(preArrangeViewport) and ComputeViewportToElementAnchorPointsDistance(pre, isForPreArrange: true).
  3. Call base arrange.
  4. Reset _pendingViewportShiftX = _pendingViewportShiftY = 0.
  5. Recompute post-arrange viewport + distance.
  6. 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/Y so 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 / ScrollViewer path 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 need ShouldReportNegativeOffsets or equivalent allowances. Document explicitly.

Acceptance criteria

Risks

  • Anchor tracking firing during user scroll can fight the user. ScrollViewer_Partial.cpp's ResetAnchorElement / m_isAnchorElementDirty handling during ViewChanging is the reference; port verbatim.
  • Many apps rely on ScrollViewer not 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

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

  1. added 2 commits that reference this issue on Apr 15, 2026
    8bd6f40
    e22a31c
  2. added theissue type on Apr 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions