Skip to content

fix(#495): break ListView SelectedIndex+UseState re-render storm; harden GridView and typed templated lists - #499

Merged
Chris Anderson (codemonkeychris) merged 2 commits into
mainfrom
fix/495-listview-loop-state-bound
Jun 1, 2026
Merged

Chris Anderson (codemonkeychris) merged 2 commits into
mainfrom
fix/495-listview-loop-state-bound

Conversation

@codemonkeychris

Copy link
Copy Markdown
Collaborator

Summary

Fixes #495 — ListView with SelectedIndex bound to UseState entered a re-render storm after the first selection (observed ~23 renders / ~47 callbacks per single click; my fixture measured 52/105 on Windows latest). Final state was consistent, but the thrash was severe.

While in the area, audited every hand-coded handler and templated-list lifecycle for the same pattern; GridView had the same root cause and a strictly worse symptom (wrong final value — lastIndex=-1 finalControlIndex=-1 after a user write of 1) and the typed templated lists had unguarded SelectionChanged trampolines + bare SelectedIndex writes. All hardened in this PR.

Root cause (ListView, GridView)

Two compounding bugs in Update:

  1. !ReferenceEquals(o.Items, n.Items) rebuilt ItemsSource on every render — idiomatic new Element[] { ... } literals always reallocate. WinUI transiently drops SelectedIndex to -1 on ItemsSource reassignment and synchronously fires SelectionChanged(-1) → leaks through to user code.
  2. Unconditional lv.SelectedIndex = n.SelectedIndex write fired a second SelectionChanged echo with no ChangeEchoSuppressor gating.

Fixes

Site Change
ListViewHandler Length-only ItemsSource rebuild; ShouldSuppress trampoline; drift-guarded BeginSuppress on Mount + Update SelectedIndex writes
GridViewHandler.Update:116 Length-only ItemsSource rebuild (echo suppression already present from #464)
TemplatedListLifecycle (ListView/GridView/FlipView) ShouldSuppress on 3 SelectionChanged trampolines; drift-guarded BeginSuppress on 3 Mount + 3 Update SelectedIndex writes (UpdateFlipView previously wrote SelectedIndex unconditionally, could silently clear with -1)

Mirrors the established GridView pattern from #464.

Patterns audited and cleared

  • .Controlled / .HandCodedControlled descriptor props (ComboBox, Pivot, RadioButtons, TabView, ListBox, FlipView, ItemsView, NavigationView, TextBox, ToggleSwitch, etc.) — already echo-suppress via value-diff arm. (Broader authority-model question for .Controlled is tracked by .Controlled descriptor entries silently clobber user input on sibling re-renders when prop is not bound to state #494, being addressed separately.)
  • CheckBox, ToggleSwitch, Slider, TextBox handlers — already canonical.
  • Expander, OverlayLifecycle CommandBarFlyout, SwipeControl, TemplatedTreeView — no storm risk (idempotent setters or no callback round-trip).

Validation

New fixtures Issue495_{ListView,GridView,TypedListView,TypedGridView}Loop_StateBound_NoLoopAfterSelection:

Pre-fix:

  • ListView: renders+=52 callbacks+=105 ❌
  • GridView: renders+=2 callbacks+=3 lastIndex=-1 finalControlIndex=-1 ❌ (wrong final value)
  • Typed lists: passed by accident (OC pipeline absorbed it) — fixes are defense-in-depth

Post-fix: all four fixtures renders+=1 callbacks+=1 lastIndex=1 finalControlIndex=1 ✅

Sweeps green:

  • All 21 ListView selftests + GridView, FlipView, TemplatedList, Selection, Echo, ValueDiff, KLR ✅
  • Full selftest suite: 0 failures ✅
  • Reactor.Tests xUnit: 9210/9210 ✅

Related

…den GridView and typed templated lists

Issue #495: ListView(items) with { SelectedIndex = index, OnSelectedIndexChanged = setIndex }
entered a re-render storm after the first selection — ~23 renders / ~47 callbacks
per single click before UseState's equality short-circuit drained the queue.

Two compounding bugs in ListViewHandler.Update:

1. !ReferenceEquals(o.Items, n.Items) rebuilt ItemsSource on every render
   because idiomatic
ew Element[] { ... } literals allocate fresh arrays.
   WinUI transiently drops SelectedIndex to -1 on ItemsSource reassignment
   and fires SelectionChanged(-1) — leaking the -1 through to user code.
2. Unconditional lv.SelectedIndex = n.SelectedIndex write fired a second
   SelectionChanged echo with no ChangeEchoSuppressor gating, so it also
   leaked back into OnSelectedIndexChanged.

Fix mirrors the GridView pattern from issue #464:
* Update: only rebuild ItemsSource when item count changes; realized
  containers re-read their item from the element tag via SetElementTag.
* Mount/Update: drift-guarded BeginSuppress around the SelectedIndex write.
* Mount: ChangeEchoSuppressor.ShouldSuppress gate at the SelectionChanged
  trampoline (defense in depth).

Audit of all hand-coded handlers found the same pattern in:
* GridViewHandler.Update: same ReferenceEquals rebuild bug. Pre-fix repro
  produced a WRONG final value (lastIndex=-1 finalControlIndex=-1 after a
  user write of 1). Fixed with length-only check (echo suppression around
  the SelectedIndex write was already present from #464).
* TemplatedListLifecycle.Mount/Update for the typed ListView<T>/GridView<T>/
  FlipView<T> peers: SelectionChanged trampolines missing ShouldSuppress;
  SelectedIndex writes bare and unguarded. Especially UpdateFlipView, which
  wrote v.SelectedIndex = n.GetSelectedIndex() unconditionally and could
  silently clear selection with a -1. Defense-in-depth applied.

Descriptor .Controlled/.HandCodedControlled entries (ComboBox, Pivot,
RadioButtons, TabView, ListBox, FlipView, ItemsView, NavigationView,
TextBox, ToggleSwitch, etc.) already echo-suppress via the value-diff
arm — unchanged. (The broader force-assert authority-model question for
.Controlled is tracked by #494.)

Validation:
* New fixtures Issue495_{ListView,GridView,TypedListView,TypedGridView}Loop
  reproduce the storm pre-fix and confirm bounded renders/callbacks +
  correct final value post-fix.
* All 21 ListView, GridView, FlipView, TemplatedList, Selection, Echo,
  and ValueDiff selftests pass.
* Full selftest suite: 0 failures.
* Reactor.Tests xUnit suite: 9210/9210 pass.

Closes #495.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

public override Element Render()
{
RenderCount++;

public override Element Render()
{
RenderCount++;

public override Element Render()
{
RenderCount++;

public override Element Render()
{
RenderCount++;

Copilot AI left a comment

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.

Pull request overview

Fixes issue #495 — a ListView (and analogously GridView / typed templated lists) re-render storm when SelectedIndex is bound to UseState. Two compounding causes are addressed: (1) ItemsSource was rebuilt on every render because the gate used ReferenceEquals against idiomatic fresh new Element[] literals, causing WinUI to transiently set SelectedIndex = -1 and fire a stray SelectionChanged; (2) the post-rebuild programmatic SelectedIndex write was unsuppressed and produced its own echo. The PR weakens the rebuild gate to a length check and arms ChangeEchoSuppressor (drift-guarded BeginSuppress + ShouldSuppress in trampolines) around all SelectedIndex writes for simple ListView/GridView and the typed ListView<T> / GridView<T> / FlipView<T> lifecycles, mirroring the existing GridView issue-#464 pattern.

Changes:

  • Replace ReferenceEquals(o.Items, n.Items) with o.Items.Length != n.Items.Length as the ItemsSource rebuild gate in ListViewHandler.Update / GridViewHandler.Update.
  • Add ShouldSuppress to SelectionChanged trampolines and drift-guarded BeginSuppress around mount/update SelectedIndex writes in ListViewHandler and TemplatedListLifecycle (typed ListView<T> / GridView<T> / FlipView<T>).
  • Add four new selftest fixtures in ListViewLoopReproFixtures.cs covering simple ListView, simple GridView, typed ListView<T>, and typed GridView<T>.
Show a summary per file
File Description
src/Reactor/Core/V1Protocol/Handlers/ListViewHandler.cs Length-only ItemsSource gate; ShouldSuppress in SelectionChanged trampoline; drift-guarded BeginSuppress on Mount/Update SelectedIndex writes.
src/Reactor/Core/V1Protocol/Handlers/GridViewHandler.cs Length-only ItemsSource gate (echo suppression already present from #464).
src/Reactor/Core/V1Protocol/TemplatedListLifecycle.cs Adds ShouldSuppress + drift-guarded BeginSuppress for typed ListView/GridView/FlipView mount/update SelectedIndex writes.
tests/.../Fixtures/ListViewLoopReproFixtures.cs New issue-#495 regression fixtures across simple and typed ListView/GridView.
tests/.../SelfTest/SelfTestFixtureRegistry.cs Registers the four new selftest fixtures (name list + constructor switch).

Copilot's findings

Tip

Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

  • Files reviewed: 5/5 changed files
  • Comments generated: 2

Comment on lines 128 to 138
// Issue #495 — only rebuild ItemsSource when the item count actually
// changes. The previous ReferenceEquals check forced a full container
// realization cycle on every render because idiomatic Reactor authors
// allocate `new Element[] { ... }` literals (no memoization). The
// rebuild transiently drops SelectedIndex to -1 and fires a stray
// SelectionChanged(-1) — the trigger of the issue-#495 re-render
// storm. Already-realized containers re-read their item from the
// element tag via SetElementTag below; new realizations follow the
// same path through ContainerContentChanging.
if (o.Items.Length != n.Items.Length)
lv.ItemsSource = Enumerable.Range(0, n.Items.Length).ToList();
Comment on lines 116 to 130
// Issue #495 / #464 — only rebuild ItemsSource when the item count
// actually changes. The previous ReferenceEquals check forced a full
// container realization cycle on every render because idiomatic
// Reactor authors allocate `new Element[] { ... }` literals (no
// memoization). The rebuild transiently drops SelectedIndex to -1
// and synchronously fires SelectionChanged(-1) — leaking through to
// the user callback (whose trampoline only suppresses ONE echo, set
// up below to suppress the *intended* write). With the state-binding
// pattern this produced a wrong final value (the transient -1 wins).
// Already-realized containers re-read their item from the element
// tag via SetElementTag below; new realizations follow the same
// path through ContainerContentChanging. Matches the ListView fix
// in ListViewHandler.Update.
if (o.Items.Length != n.Items.Length)
gv.ItemsSource = Enumerable.Range(0, n.Items.Length).ToList();
…sient SelectionChanged echo instead

CR review (Copilot) caught a regression in the previous fix: gating the
ItemsSource rebuild on length-only would silently freeze visible item
content when callers re-render with the same item count but new per-item
content (e.g. names whose labels change but row count is stable). The
hand-coded ListView/GridView handlers have Children = null and never
reconcile realized child controls; ContainerContentChanging only fires
on (re)realization or recycle, not on a tag-only change.

Proper fix: keep the original !ReferenceEquals(o.Items, n.Items) rebuild
gate so WinUI recycles + re-realizes containers (CCC re-fires

econciler.Mount for each item) — but arm BeginSuppress immediately
before the swap so the transient SelectionChanged(-1) WinUI fires when
an active selection is cleared by the reassignment is consumed by the
trampoline's ShouldSuppress gate. Only arm when there's actually a
selection to clear (SelectedIndex >= 0) — otherwise the token strands
and swallows the next real user input.

Added two regression fixtures to lock the contract down:
* Issue495_ListView_SameLengthContentChange_RefreshesContainers
* Issue495_GridView_SameLengthContentChange_RefreshesContainers

Both bump a label generation between renders and assert the displayed
text actually transitions from "row0-gen0" to "row0-gen1". Pre-fix
(length-only): both fail (gen1 text never appears, gen0 still visible).
Post-fix: both pass.

Also fixes the misleading comment that claimed realized containers
re-read their item from the element tag — they don't; the rebuild is
what triggers re-mount via CCC.

All 6 Issue495 fixtures pass (4 loop + 2 same-length); full selftest
suite: 0 failures.
@codemonkeychris
Chris Anderson (codemonkeychris) merged commit b1dd437 into main Jun 1, 2026
16 checks passed
@codemonkeychris
Chris Anderson (codemonkeychris) deleted the fix/495-listview-loop-state-bound branch June 1, 2026 03:36
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.

ListView with SelectedIndex bound to UseState enters re-render loop on first selection

2 participants