Skip to content

[WinUI][CV2] Fix for Null Item Handling - follow-ups from CollectionView2 Windows handler (#34600) - #36170

Closed
SuthiYuvaraj wants to merge 11 commits into
net11.0from
Fix-nullItemCV2
Closed

SuthiYuvaraj wants to merge 11 commits into
net11.0from
Fix-nullItemCV2

Conversation

@SuthiYuvaraj

Copy link
Copy Markdown
Contributor

Note

Are you waiting for the changes in this PR to be merged?
It would be very helpful if you could test the resulting artifacts from this PR and let us know in a comment if this change resolves your issue. Thank you!

Issue Description

Null-item false selection

RootCause
UpdateVisualStates was incorrectly computing selection state for null items. A null item could appear visually selected or deselected incorrectly because the container-to-item lookup did not account for null values.

Fix Description
Added a null guard so null items are checked by container identity rather than item equality.

Grouped null-Replace desync

RootCause
When a grouped source fired an INCC Replace with a null new-item, HandleGroupItemsReplace skipped creating a new ItemTemplateContext2 for that slot. This left the flat-list mirror out of sync with the source.

Fix Description
Fixed by always creating a fresh ItemTemplateContext2(template, null) for null replacement items instead of skipping.

Null drag stale index

RootCause
During drag-and-drop reorder, if GetContainerIndex failed to resolve the dragged container (returning -1), the stale index was used in subsequent drop calculations causing an incorrect reorder or index out of range.

Fix Description
Added a reset fallback: if _draggedSourceIndex < 0 the drag state is cleaned up rather than proceeding with a bad index.

Issues Fixed

Fixes #36068

Tested the behaviour in the following platforms

  • Android
  • Windows
  • iOS
  • Mac

Output Screenshot

Before Issue Fix After Issue Fix
BeforenullItem.mov
CV2AfterFix.mov

@github-actions

Copy link
Copy Markdown
Contributor

🚀 Dogfood this PR with:

⚠️ WARNING: Do not do this without first carefully reviewing the code of this PR to satisfy yourself it is safe.

curl -fsSL https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.sh | bash -s -- 36170

Or

  • Run remotely in PowerShell:
iex "& { $(irm https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.ps1) } 36170"

@dotnet-policy-service dotnet-policy-service Bot added the partner/syncfusion Issues / PR's with Syncfusion collaboration label Jun 26, 2026
@github-actions github-actions Bot added area-controls-collectionview CollectionView, CarouselView, IndicatorView platform/windows labels Jun 26, 2026
@kubaflo

This comment has been minimized.

@github-actions github-actions Bot added the s/agent-review-in-progress AI review is currently running for this PR label Jun 27, 2026

@MauiBot MauiBot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Expert Review — 4 findings

See inline comments for details.

ItemsView.SelectedItem = selectedItem;

ItemsView.SelectionChanged += VirtualSelectionChanged;
_ignoreVirtualSelectionChange = false;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[moderate] Handler Mapper and Property Patterns — _ignoreVirtualSelectionChange and the temporary SelectionChanged unsubscribe are not restored in a finally block. If ItemsView.SelectedItem = selectedItem throws from a bindable-property callback, validation path, or user PropertyChanged handler, the handler stays with SelectionChanged detached and _ignoreVirtualSelectionChange == true, so subsequent virtual/platform selection changes are silently suppressed for the handler lifetime. Wrap the assignment in try/finally that always reattaches VirtualSelectionChanged and resets _ignoreVirtualSelectionChange.

return false;
// Blank container (no ElementWrapper) represents a null data item.
// It matches when the dragged item is also null.
return item is null;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[major] Logic and Correctness — Treating any blank ItemContainer as bound to null makes a null-item drag match every realized null row, not just the source row. During live reorder, ItemsRepeater_ElementPrepared calls IsContainerBoundToDraggedItem after ApplyDragAffordance, so with two null items all blank null containers get Opacity = 0 and IsHitTestVisible = false. Use the instance state available there (for example container.Tag is int t && t == _draggedSourceIndex, or ItemsRepeater.GetElementIndex) for blank/null containers instead of value matching on null.

{
if (_draggedItem is null || _mauiVirtualView is not GroupableItemsView groupableView)
// _draggedSourceIndex < 0 means no active drag; _draggedItem may be null for null data rows.
if (_draggedSourceIndex < 0 || _mauiVirtualView is not GroupableItemsView groupableView)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[major] Logic and Correctness — Allowing _draggedItem == null into grouped reorder still leaves source-group discovery based on value equality (ReferenceEquals(groupItem, _draggedItem) || Equals(groupItem, _draggedItem)). In grouped data with more than one null item, this picks the first null in the first matching group rather than the row whose container started the drag, so dragging Group B[0] == null can move Group A's null item instead. For null items, map _draggedSourceIndex (the captured flat row index, accounting for group headers/footers) back to source group/item instead of searching by value.

{
var tagItem = GetItemAtIndex(tagIndex, sourceList);
if (containerItem is not null && Equals(tagItem, containerItem))
if (Equals(tagItem, containerItem))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[major] Logic and Correctness — The tag validation now accepts Equals(null, null), so a stale Tag on a null-item container is considered valid whenever the old index also contains any null item. If that check does not return, the new linear-search fallback has the same ambiguity (IndexOfItem(null, sourceList) returns the first null). After a reorder or recycled-container handoff, a second drag on a later null row can therefore capture the wrong _draggedSourceIndex and move the wrong data item. Use ItemsRepeaterControl.GetElementIndex(container as ItemContainer) for null/blank containers before any value-equality fallback.

@MauiBot MauiBot added s/agent-fix-pr-picked AI could not beat the PR fix - PR is the best among all candidates s/agent-reviewed PR was reviewed by AI agent workflow (full 4-phase review) labels Jun 27, 2026
MauiBot

This comment was marked as outdated.

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

This PR addresses several edge cases in the WinUI CollectionView2 (Items2) handler when the bound ItemsSource contains null elements, focusing on selection visual state correctness, grouped Replace consistency, and drag-and-drop reorder robustness.

Changes:

  • Adjust selection-state computation to avoid false “Selected” visuals when item data is null.
  • Fix grouped INCC Replace handling so null replacement items still get a fresh ItemTemplateContext2 (keeping the flattened mirror in sync).
  • Improve drag/drop reorder handling around null items by using _draggedSourceIndex as the drag-active sentinel and updating index/tag handling for null rows.

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 3 comments.

File Description
src/Controls/src/Core/Handlers/Items2/Windows/MauiItemsView.DragDrop.cs Updates drag/drop sentinels and container index/tag logic to correctly support null items during reorder.
src/Controls/src/Core/Handlers/Items2/Windows/ItemFactory.cs Adds a null-item fast path to render blank rows and align row sizing behavior with CV1 expectations.
src/Controls/src/Core/Handlers/Items2/Windows/GroupedItemTemplateCollection2.cs Ensures grouped Replace always creates a new ItemTemplateContext2 even when the new item is null.
src/Controls/src/Core/Handlers/Items2/CollectionViewHandler2.Windows.cs Prevents WinUI null selection from being immediately undone by suppressing the SelectedItem round-trip during platform-driven selection updates.

Comment on lines +1207 to 1215
// The containerItem is not null guard was intentionally removed: null-item
// containers (valid null data rows) need tag validation too, and
// Equals(null, null) correctly returns true for them.
if (container.Tag is int tagIndex && sourceList is not null &&
tagIndex >= 0 && tagIndex < sourceList.Count)
{
var tagItem = GetItemAtIndex(tagIndex, sourceList);
if (containerItem is not null && Equals(tagItem, containerItem))
if (Equals(tagItem, containerItem))
{
@kubaflo

This comment has been minimized.

@github-actions github-actions Bot added the s/agent-review-in-progress AI review is currently running for this PR label Jun 29, 2026

@MauiBot MauiBot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Expert Review — 6 findings

See inline comments for details.

@github-actions github-actions Bot added the s/agent-review-in-progress AI review is currently running for this PR label Aug 5, 2026

@MauiBot MauiBot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Expert Review — 15 findings

See inline comments for details.

using Microsoft.Maui.Handlers;
using Microsoft.Maui.Platform;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[critical] Regression Prevention - This using block breaks the Windows DeviceTests compilation, so neither new test can ever run.

  1. using Microsoft.UI.Xaml.Controls; (this line) collides with the pre-existing using Microsoft.Maui.Controls; on line 7. This file already constructs new Grid() on line 170 and new Grid { ... } on line 364, and Grid exists in both namespaces -> CS0104: 'Grid' is an ambiguous reference between 'Microsoft.Maui.Controls.Grid' and 'Microsoft.UI.Xaml.Controls.Grid'. The file's existing convention already solves this for the WinUI types it needs (WItemsView, WSetter aliases on lines 18-19) - do the same for ItemContainer (e.g. using WItemContainer = Microsoft.UI.Xaml.Controls.ItemContainer;) instead of importing the whole namespace.
  2. ConfigureMauiHandlers (used on lines 435 and 479) is an extension method in Microsoft.Maui.Hosting (HandlerMauiAppBuilderExtensions). Usings are per-file, and the using Microsoft.Maui.Hosting; the rest of this partial class relies on lives in CollectionViewTests.cs, not here -> CS1061 on builder.ConfigureMauiHandlers(...). Add using Microsoft.Maui.Hosting; to this file.

// tap, skip the round-trip back to UpdatePlatformSelection. Without this guard,
// tapping a null item causes: WinUI selects null → SelectedItem = null →
// MapSelectedItem → UpdatePlatformSelection → DeselectAll (undoes the selection).
if (handler._ignoreVirtualSelectionChange)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[major] Logic and Correctness / Regression Prevention - This guard is too broad and breaks the most common MAUI selection idiom on Windows CV2.

Element.OnBindablePropertySet deliberately defers UpdateHandlerValue until after property.PropertyChanged fires (see Element.cs:694-703 and the comment at Element.cs:711-719). SelectableItemsView raises the public SelectionChanged event from that PropertyChanged callback. So everything the app does inside its SelectionChanged handler executes inside the _ignoreVirtualSelectionChange window opened in UpdateVirtualSingleSelection, and MapSelectedItem for both the outer and any nested write is suppressed.

Concrete failing scenario - the canonical tap-then-clear pattern:

cv.SelectionChanged += (s, e) => { Navigate(e.CurrentSelection[0]); cv.SelectedItem = null; };
  1. User taps Item 1 -> PlatformSelectionChanged -> UpdateVirtualSingleSelection sets _ignoreVirtualSelectionChange = true.
  2. ItemsView.SelectedItem = Item 1 -> SelectionChanged -> app sets SelectedItem = null -> nested MapSelectedItem suppressed.
  3. Outer MapSelectedItem suppressed too (still inside the try).
  4. UpdatePlatformSelection() never runs, so PlatformView.DeselectAll() never runs. The WinUI ItemContainer stays visually selected and PlatformView.SelectedItem stays non-null.
  5. Tapping the same row again produces no WinUI SelectionChanged, so the app handler never fires for that item again.

Before this PR both writes reached UpdatePlatformSelection and the platform was correctly deselected.

Suggested fix: make the guard value-scoped rather than time-scoped - record the value being written (e.g. _pendingVirtualSelection) and in MapSelectedItem only skip when ReferenceEquals(itemsView.SelectedItem, pending); otherwise fall through to UpdatePlatformSelection() so re-entrant app writes still propagate. Also save/restore the previous flag value in the finally on line 348 rather than hard-assigning false, so a nested UpdateVirtualSingleSelection cannot clear the outer frame's guard early.

// Prevents MapSelectedItem from calling UpdatePlatformSelection when
// UpdateVirtualSingleSelection is writing SelectedItem in response to a
// platform tap — otherwise the null-item WinUI selection gets undone.
bool _ignoreVirtualSelectionChange;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[moderate] Cross-Platform Behavioral Consistency - The new flag is only honoured for SelectionMode.Single. UpdateVirtualMultipleSelection does not set it, MapSelectedItems has no equivalent guard, and ExtractPlatformSelectedItems() explicitly drops nulls (if (selectedItem is not null) result.Add(...), line 427).

So in SelectionMode.Multiple a null row can now be checked in the WinUI UI (it gets a real, selectable ItemContainer from the new ItemFactory path) but it never lands in SelectedItems, and the first subsequent MapSelectedItems -> UpdatePlatformSelection -> DeselectAll() visually undoes the check. That is exactly the round-trip this PR fixes for Single mode, left in place for Multiple.

Either extend the fix to multi-select or explicitly document/assert that null items are not selectable in Multiple mode, and add a device test pinning the chosen behaviour.

foreach (var _ in groupSrcItems)
{
if (ReferenceEquals(groupItem, _draggedItem) || Equals(groupItem, _draggedItem))
if (flatSrcPos == _draggedSourceIndex)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[major] Logic and Correctness - Replacing the value-equality search with pure flat-index arithmetic makes grouped reorder depend on assumptions that do not hold for every grouped configuration, and it removes the safety net the flat path still has.

  1. The flat source does not always contain header/footer rows. hasHeaders/hasFooters are derived from GroupHeaderTemplate/GroupFooterTemplate, but _draggedSourceIndex indexes the repeater's flat source (GetContainerIndex -> GetSourceList() -> ItemsSource). That flat source only contains header/footer entries when ItemsViewHandler2.CreateCollectionViewSource takes the TemplatedItemSourceFactory2.CreateGrouped branch (ItemsViewHandler2.Windows.cs:347-355). When IsGrouped=true and GroupHeaderTemplate is set but ItemTemplate is null, it falls through to FlattenGroupedItemsSource(itemsSource) (ItemsViewHandler2.Windows.cs:380-385), which emits no header/footer rows. flatSrcPos then over-counts by one per group and this comparison resolves to the wrong (sourceGroupIndex, sourceItemIndex) - the drop moves a different row.
  2. String groups desync the walk. GroupedItemTemplateCollection2.RebuildFlatList skips a group when group is string || group is not IEnumerable (GroupedItemTemplateCollection2.cs:129-130). The guard on line 873 only skips not IEnumerable. A string group is IEnumerable<char>, so it contributes 1 header + N chars + 1 footer to flatSrcPos that the real flat list never contained, and every later group maps to the wrong index. The pre-existing target-mapping loop at line 916 has the same gap.
  3. No validation or fallback. PerformReorder validates _draggedSourceIndex against the live item and falls back to IndexOfItem when it is stale (line 765-777); this grouped path now trusts the index unconditionally. A collection change between DragStarting and Drop silently moves the wrong item.

Suggest deriving the group/item position from the flat collection that _draggedSourceIndex actually indexes (walk GetSourceList() / the GroupedItemTemplateCollection2) instead of re-deriving it from groupsList + template flags, and validating the resolved item against _draggedItem when _draggedItem is not null before mutating.

if (!_canReorderItems || _draggedItem is null || _insertionIndex < 0 || _mauiVirtualView is null)
// _draggedSourceIndex < 0 means no active drag. _draggedItem may be null for
// null data rows, so we cannot use _draggedItem is null as the guard here.
if (!_canReorderItems || _draggedSourceIndex < 0 || _insertionIndex < 0 || _mauiVirtualView is null)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[moderate] Null Safety and Defensive Coding - Swapping the drag-in-progress sentinel from _draggedItem is not null to _draggedSourceIndex >= 0 is right for null rows, but _draggedSourceIndex is now assigned from a fallible lookup: _draggedSourceIndex = GetContainerIndex(itemContainer) (line 453), and GetContainerIndex can return -1 (the new null branch at line 1252 returns -1 when GetElementIndex fails and Tag is not an int; the non-null path can also fall through to allContainers.IndexOf(container) returning -1).

When that happens DragStarting has already returned without setting args.Cancel, so WinUI starts a real drag, but every downstream guard (ItemsRepeater_ElementPrepared lines 326/335, DimNonSourceContainers line 1767, this Drop guard, PerformReorder line 755, PerformGroupedReorder line 854) now treats it as no drag in progress: no dim, no source hiding, and the drop is silently discarded. Previously a non-null _draggedItem kept all of those alive.

Guard at the source - after computing the index in DragStarting, cancel the drag if it is negative:

_draggedSourceIndex = GetContainerIndex(itemContainer);
if (_draggedSourceIndex < 0) { args.Cancel = true; return; }

var newItem = CreateItemContext(e.NewItems[i]!);
// Always create a new context even for null new items — skipping the slot update
// would leave the stale old ItemTemplateContext2 in the flat list (desync).
var newItem = CreateItemContext(e.NewItems[i]);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[moderate] Regression Prevention - The Replace-with-null desync fix here is correct (previously oldItems.Count != newItems.Count in the raised NotifyCollectionChangedEventArgs and the stale ItemTemplateContext2 was left in the flat list), but nothing in this PR exercises it.

The grouped path received two behaviour-affecting changes in this PR - this one and the switch of PerformGroupedReorder to positional _draggedSourceIndex matching (MauiItemsView.DragDrop.cs:862-900) - yet every added test (2 device tests, 2 UI tests, 1 HostApp page) uses a flat, non-grouped source. Grouped + null items with group headers/footers is precisely the case the new flat-index arithmetic was written for (see the comment on line 864 about multiple null items across groups), and it is completely uncovered.

Please add at least: (a) a test that replaces a group item with null and asserts the flat collection stays in sync in Items.Count and index positions, and (b) a grouped variant of the HostApp reorder page with a null item in a group so the header/footer offset arithmetic in PerformGroupedReorder is exercised.

var nullContainer = containers[1];
var exception = await Record.ExceptionAsync(async () =>
{
nullContainer.IsSelected = true;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[major] Regression Prevention - This test passes with and without the _ignoreVirtualSelectionChange fix, so it does not guard the regression.

collectionView.SelectedItem is null before the tap. UpdateVirtualSingleSelection then assigns ItemsView.SelectedItem = null (the unwrapped null item). BindableObject.SetValueActual short-circuits on sameValue (Equals(null, null) is true and SelectedItemProperty does not use RaiseOnEqual), so no PropertyChanged fires, UpdateHandlerValue is never called, and MapSelectedItem never runs - with or without the new guard. DeselectAll() can therefore never undo the selection in this scenario.

The real failing scenario requires a transition to null: select a real item first, then select the null row, so SelectedItem changes Item 1 -> null and MapSelectedItem -> UpdatePlatformSelection -> DeselectAll() fires. Please add that step:

containers[0].IsSelected = true;              // SelectedItem = Item 1
await Task.Delay(100);
containers[1].IsSelected = true;              // SelectedItem: Item 1 -> null (real change)
await Task.Delay(100);
Assert.True(containers[1].IsSelected);        // fails on main, passes with the fix

Also note Assert.Null(collectionView.SelectedItem) and Assert.False(nullContainer.IsSelected) (line 540, immediately after setting it to false) are non-discriminating and pass trivially.

// The null-item container (index 1) should have non-zero height (blank row)
var nullContainer = containers[1];
var bounds = nullContainer.GetBoundingBox();
Assert.True(bounds.Height > 0, $"Null item container should have non-zero height, got {bounds.Height}");

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[major] Regression Prevention - NullItem_RendersBlankRow also passes without the ItemFactory change, so it does not pin the new behaviour.

Before this PR a null item still produced an ItemContainer: GetElement fell through to the normal path, created the ElementWrapper, and set view.BindingContext = templateContext.Item (null). The Label has HeightRequest = 40, so bounds.Height > 0 held then too. The assertion cannot distinguish the old realized-template row from the new blank row.

Two gaps to close:

  1. Assert what actually changed - the container is blank: Assert.Null(nullContainer.Child); (the new path returns an ItemContainer with no ElementWrapper), and optionally that its height matches the new MinHeight = 32 rather than the template height.
  2. containers[1] is never verified to be the null row. GetChildren<ItemContainer>() is a VisualTreeHelper walk; ItemsRepeater child order is not guaranteed to follow item index once containers are recycled. Unlike the selection test, nothing here fails loudly if the index is wrong - the test silently measures a real item. Resolve the container via ItemsRepeaterControl.GetElementIndex/TryGetElement(1) or by checking Child is null.

Also, per repo test guidance the fixed await Task.Delay(500) on lines 459/510 should be a deterministic wait (AssertEventually/WaitForMainThread) - arbitrary sleeps are the main source of CV flakiness on Windows CI.

App.WaitForElement("ReorderItemLabel3");

var initialOrder = App.WaitForElement("ReorderStatusLabel").GetText();
Assert.That(initialOrder, Is.EqualTo("Item A, null, Item B, Item C"));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[major] Regression Prevention - These two tests are order-dependent and the second one will fail.

UITestBase.ResetAfterEachTest defaults to false (src/TestUtils/src/UITest.NUnit/UITestBase.cs:12) and this class does not override it, so FixtureSetup() -> TryToResetTestState() -> NavigateToIssue(...) runs only once in [OneTimeSetUp]. Both tests therefore share the same live page and the same ObservableCollection instance.

NUnit runs methods in alphabetical order, so DraggingNullItemRowDoesNotCrashAndReorders mutates Items first; this assertion then sees the already-reordered text and fails with e.g. Expected: 'Item A, null, Item B, Item C' But was: 'Item A, Item B, Item C, null'. The derived nullRowY (line 63) is also computed from an ordering that no longer holds.

Fix by either adding protected override bool ResetAfterEachTest => true;, adding a reset button/[SetUp] that restores Items, or merging the two scenarios into a single test that asserts the order after each drag.

App.WaitForElement("ReorderStatusLabel");
var reorderedText = App.WaitForElement("ReorderStatusLabel").GetText();

Assert.That(reorderedText, Is.Not.EqualTo(initialOrder),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[moderate] Regression Prevention - The assertions cannot discriminate the bug this PR fixes.

The null row has no AutomationId (it renders as a bare ItemContainer with no template content), so the test infers its position from the gap between ReorderItemLabel0 and ReorderItemLabel2 (line 32). That gap also contains Item A's Padding=16 bottom, its Margin=0,0,0,8, and Item B's top padding, so the drag can easily grab Item A instead of the blank row.

With the current checks - Is.Not.EqualTo(initialOrder), Has.Length.EqualTo(4), Does.Contain('null') - dragging the wrong row still changes the order, still yields 4 entries, and still contains null, so the test passes while the null-row drag path is broken. This is the exact failure mode the GetContainerIndex/UpdateAllContainerIndices -> GetElementIndex work exists to prevent.

Assert the exact expected result instead, e.g. Assert.That(reorderedText, Is.EqualTo("Item A, Item B, Item C, null")) here and the corresponding exact order on line 73. Consider also adding a second null entry to the fixture - with a single null, a first null wins fallback bug is indistinguishable from correct behaviour - and giving the blank row a locatable anchor rather than deriving coordinates from neighbouring labels.

@MauiBot

This comment has been minimized.

@MauiBot MauiBot removed the s/agent-review-in-progress AI review is currently running for this PR label Aug 5, 2026
@kubaflo

kubaflo commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

/review -b improved-reviewer -p windows

1 similar comment
@kubaflo

This comment has been minimized.

@github-actions github-actions Bot added the s/agent-review-in-progress AI review is currently running for this PR label Aug 5, 2026
@MauiBot MauiBot added the s/agent-review-incomplete AI review did not complete all expected phases label Aug 6, 2026

@MauiBot MauiBot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Expert Review — 12 findings

See inline comments for details.

using Microsoft.Maui.Handlers;
using Microsoft.Maui.Platform;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[critical] Logic and Correctness — This using Microsoft.UI.Xaml.Controls; breaks compilation of the Windows DeviceTests project. The file already has using Microsoft.Maui.Controls;, and both namespaces export types named SelectionMode (WinUI''s ListBox selection enum, confirmed present in Microsoft.WinUI.dll) and Grid. That makes every pre-existing bare use ambiguous → CS0104:

  • SelectionMode at lines 46, 88 (pre-existing) and 498 (new)
  • Grid at lines 170, 186, 364 (pre-existing)

Nothing in the file or project aliases these away (no using SelectionMode = ..., no global usings). The rest of the file already uses the fully-qualified form for WinUI types (UI.Xaml.Controls.ListView line 199, UI.Xaml.Controls.TextBlock line 209), so the new ItemContainer references should follow that convention or add an alias (using WItemContainer = Microsoft.UI.Xaml.Controls.ItemContainer;) instead of importing the whole namespace.

// tap, skip the round-trip back to UpdatePlatformSelection. Without this guard,
// tapping a null item causes: WinUI selects null → SelectedItem = null →
// MapSelectedItem → UpdatePlatformSelection → DeselectAll (undoes the selection).
if (handler._ignoreVirtualSelectionChange)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[major] Handler Mapper and Property Patterns — This guard is broader than the round-trip it is meant to break, and it swallows re-entrant SelectedItem writes made by application code.

SelectableItemsView.SelectedItemPropertyChanged runs the BindableProperty changed callback synchronously inside SetValue, and that callback executes SelectionChangedCommand and raises the public SelectionChanged event (src/Controls/src/Core/Items/SelectableItemsView.cs, SelectionPropertyChanged). So any user handler runs while _ignoreVirtualSelectionChange == true.

Concrete scenario (very common MAUI pattern — clearing selection so the same row can be tapped twice):

  1. SelectedItem is "A"; user taps "B".
  2. UpdateVirtualSingleSelection sets the flag and assigns SelectedItem = "B".
  3. The synchronous SelectionChanged/SelectionChangedCommand handler does cv.SelectedItem = null.
  4. That nested write''s MapSelectedItem hits this early return, and so does the outer one.
  5. finally clears the flag but performs no reconciliation.

Result: MAUI SelectedItem is null while the WinUI container for "B" stays visually selected, and nothing re-syncs. Before this change, the nested MapSelectedItem → UpdatePlatformSelection → DeselectAll kept the two in sync. Consider scoping the suppression to the single assignment (e.g. compare the value the handler itself wrote and re-run UpdatePlatformSelection in the finally when ItemsView.SelectedItem no longer matches it), or fixing the root cause noted below.

ItemsView.SelectionChanged += VirtualSelectionChanged;
try
{
ItemsView.SelectedItem = selectedItem;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[moderate] Logic and Correctness — The null-row selection this PR enables is not durable, because SelectedItem == null remains ambiguous between "the null item is selected" and "nothing is selected".

UpdatePlatformSelection (line 464) unconditionally does if (ItemsView.SelectedItem is null) PlatformView.DeselectAll();. The new _ignoreVirtualSelectionChange flag only covers the synchronous window of this one assignment, so the very next call to UpdatePlatformSelection from any other path silently drops the selection:

  • MapSelectionMode (line 106),
  • MapSelectedItems (line 94),
  • UpdateItemsSource (line 226) on any items-source refresh,
  • the _selectionDirty re-sync in OnPlatformViewLoaded (line 197) when the page is navigated away from and back.

The device test added in this PR only asserts immediately after the tap, so it cannot catch this. Please either make the null-item selection explicitly representable (e.g. track the selected index on the handler and consult it in UpdatePlatformSelection) or document/limit that a null row''s selection is transient.

// matching CV1 behaviour (ItemContentControl.Realize() returns early when
// dataContext is null). Header/footer items fall through to the normal
// path so they can inherit the parent ItemsView.BindingContext.
if (templateContext.Item is null && !templateContext.IsHeader && !templateContext.IsFooter)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[moderate] Cross-Platform Behavioral Consistency — Short-circuiting here means a null data item no longer inflates the ItemTemplate at all on Windows CV2, which diverges from Android and iOS.

On Android (Items/Android) and iOS (Items2/iOS) a null item still realizes the template with a null BindingContext, so a template containing static/non-bound content (a fixed Label, an icon, a FallbackValue/TargetNullValue binding, or a converter that maps null to placeholder text) renders normally. After this change the same app shows an empty 32px strip on Windows only. The comment justifies the behaviour by matching CV1 Windows, but the Items/ handler is not the cross-platform contract — the other two platforms are.

If the goal is only to avoid the crash, the narrower fix is to keep realizing the template (and to guard DataTemplateSelector.SelectTemplate(null, ...) at line 81, which is the call that actually throws for user selectors), rather than dropping the template entirely.


// CV2 has no ListViewItem wrapper, so we set both MinHeight and MinWidth on ItemContainer.
// Default sizing hints for null-data item containers in CV2, based on CV1 behavior.
return new ItemContainer

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[moderate] Layout Measure-Arrange Correctness — Hardcoding MinHeight = 32 / MinWidth = 88 for the blank container is risky for GridItemsLayout.

CreateGridView only sets MinItemWidth/MinItemHeight when the CollectionView has an explicit cross-axis WidthRequest/HeightRequest (ApplyMinItemSizeForSpan returns early otherwise, ItemsViewHandler2.Windows.cs:813). With those left at NaN, WinUI''s UniformGridLayout derives the uniform cell size from the first realized element. A collection whose first item is null therefore sizes every cell in the grid to 88×32, clipping all real items.

Please either exclude blank containers from the layout''s size derivation, or size the blank container from the measured/cached item size (CollectionViewHandler2.GetCachedFirstItemSize) rather than from two magic numbers. At minimum, add a GridItemsLayout + leading-null test — no test in this PR covers a grid layout.

}

if (item is null)
if (!hasBinding)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[moderate] Logic and Correctness — Now that every downstream guard was switched from _draggedItem is not null to _draggedSourceIndex >= 0 (lines 326, 335, 672, 755, 854, 1766), DragStarting must also validate the index it captures.

_draggedSourceIndex = GetContainerIndex(itemContainer) (line 453) can return -1: the new null-item branch returns -1 when GetElementIndex fails and Tag is not an int, and the final fallback returns allContainers.IndexOf(container) which is -1 for a container not found in the visual-tree walk. In that case the drag is not cancelled — args.Cancel is left false and the deferred callback at line 470 still sets _sourceContainer.Opacity = 0 — but ScrollViewer_Drop immediately bails on _draggedSourceIndex < 0, so the user sees the row vanish, drags, drops, and nothing reorders. Add if (_draggedSourceIndex < 0) { args.Cancel = true; return; } after the index is captured.

foreach (var _ in groupSrcItems)
{
if (ReferenceEquals(groupItem, _draggedItem) || Equals(groupItem, _draggedItem))
if (flatSrcPos == _draggedSourceIndex)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[moderate] Regression Prevention and Test Coverage — This rewrites source resolution for all grouped reorders (not just null items) from value-equality to flat-index arithmetic, yet the PR adds no grouped test at all — the sample page, the UI tests and both device tests are flat/ungrouped.

Two behavioural risks introduced by the arithmetic:

  1. It now depends on _draggedSourceIndex being in the same flat index space as the repeater. That holds only because GetSourceList() prefers the WinUI-side ItemsSource (the GroupedItemTemplateCollection2); if that ever falls back to _mauiVirtualView.ItemsSource (line 1059), the index is a group index and this loop resolves the wrong row.
  2. The skip condition diverges from the flat list builder: GroupedItemTemplateCollection2.RebuildFlatList skips group is string || group is not IEnumerable (line 129), while this loop only skips is not IEnumerable. A string group is not represented in the flat list but is counted here, desynchronising every subsequent index.

Please add a grouped drag-reorder regression test (with and without GroupHeaderTemplate/GroupFooterTemplate) covering both a null item and a normal item, since the previous value-equality path is being removed.

static bool IsContainerBoundToItem(ItemContainer container, object? item)
{
if (container.Child is not ElementWrapper wrapper || wrapper.VirtualView is not View view)
{

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[minor] Complexity Reduction — This branch is unreachable from the only caller and over-matches if it ever becomes reachable.

IsContainerBoundToDraggedItem (line 568) already returns via the container.Child is not ElementWrapper Tag comparison before delegating here, so the "blank container (no ElementWrapper)" case described in the comment can never reach this code. The condition that does reach it is Child is ElementWrapper but VirtualView is not View — a partially realized container — and returning item is null there means every such container is treated as the drag source (opacity 0, hit-testing off) during a null-item drag. Either delete the branch or restrict it to container.Child is null.

App.WaitForElement("ReorderStatusLabel");
var reorderedText = App.WaitForElement("ReorderStatusLabel").GetText();

Assert.That(reorderedText, Is.Not.EqualTo(initialOrder),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[major] Regression Prevention and Test Coverage — These assertions cannot discriminate the scenario under test from a completely different drag, in both test methods (lines 39-44 and 74-79).

The drag origin is derived geometrically (nullRowY = (itemARect.Bottom + itemBRect.Top) / 2f, line 32) from two label rects, so the grab point depends on the HeightRequest="70" grid, the Margin="0,0,0,8", the label font size, and the new hardcoded MinHeight = 32 on the blank container in ItemFactory. If any of those shift and the press lands on "Item A" or "Item B" instead of the blank row, all three assertions still pass: Is.Not.EqualTo(initialOrder) is satisfied by any reorder, Has.Length.EqualTo(4) is satisfied by every non-destructive move, and Does.Contain("null") is satisfied as long as the null entry still exists anywhere. The test would go green while never exercising the null-row drag path this PR fixes.

Assert the exact expected string (e.g. Is.EqualTo("Item A, Item B, Item C, null") for the first test and the corresponding order for the second), so the test fails when the wrong row is dragged or the null row lands in the wrong slot.

Assert.True(containers.Count >= 3, $"Expected at least 3 containers, got {containers.Count}");

// The null-item container (index 1) should have non-zero height (blank row)
var nullContainer = containers[1];

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[moderate] Regression Prevention and Test Coverage — NullItem_RendersBlankRow cannot fail for the reason it is named.

Three problems:

  1. containers[1] assumes GetChildren<ItemContainer>() returns the containers in item order. That is visual-tree child order from ItemsRepeater, which realizes and recycles elements in arbitrary order — there is no guarantee index 1 is the null row. ItemsRepeaterControl.GetElementIndex (which this PR itself relies on as "the authoritative repeater position") is the correct way to locate it.
  2. Assert.True(bounds.Height > 0) is vacuous: the fix hardcodes MinHeight = 32 on the blank container and every other container here holds a 40px Label, so the assertion passes for any of the three containers.
  3. Nothing asserts the row is actually blank (no ElementWrapper/no template content), which is the behaviour being introduced.

Also replace await Task.Delay(500) (line 459) with the deterministic helpers used elsewhere in this project (AssertHelpers / WaitForUIUpdate) — arbitrary delays are a known source of device-test flakiness.

@MauiBot

This comment has been minimized.

@MauiBot MauiBot removed the s/agent-review-in-progress AI review is currently running for this PR label Aug 6, 2026

@kubaflo kubaflo 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.

Could you please check the failing tests and ai's suggestions?

@kubaflo

This comment has been minimized.

@github-actions github-actions Bot added the s/agent-review-in-progress AI review is currently running for this PR label Aug 8, 2026
@MauiBot MauiBot added s/agent-changes-requested AI agent recommends changes - found a better alternative or issues and removed s/agent-review-incomplete AI review did not complete all expected phases labels Aug 8, 2026
MauiBot

This comment was marked as outdated.

@MauiBot MauiBot removed the s/agent-review-in-progress AI review is currently running for this PR label Aug 8, 2026
@kubaflo

This comment has been minimized.

@MauiBot MauiBot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Expert Review — 15 findings

See inline comments for details.

using Microsoft.Maui.Handlers;
using Microsoft.Maui.Platform;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[critical] Regression Prevention and Test Coverage — Adding using Microsoft.UI.Xaml.Controls; to this file breaks compilation of the Windows Controls.DeviceTests project. The namespace collides with Microsoft.Maui.Controls types already imported here, producing CS0104 ambiguities for SelectionMode, Grid, and ColumnDefinition used by the pre-existing tests in this file, and the file is also missing the namespace required for ConfigureMauiHandlers. Concrete scenario: dotnet build src/Controls/tests/DeviceTests -f net10.0-windows... fails with 14 errors, so none of the CollectionView Windows device tests (pre-existing or the two added here) can run — the new tests provide zero regression signal and the project is left red. Fix by aliasing (e.g. using WItemContainer = Microsoft.UI.Xaml.Controls.ItemContainer;) instead of importing the whole WinUI namespace, and add the missing Microsoft.Maui.Hosting using.

Assert.True(containers.Count >= 3, $"Expected at least 3 containers, got {containers.Count}");

// The null-item container (index 1) should have non-zero height (blank row)
var nullContainer = containers[1];

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[moderate] Regression Prevention and Test Coverage — containers[1] assumes the visual-child enumeration order of the ItemsView/ItemsRepeater matches item order. ItemsRepeater recycles and re-parents realized containers, so GetChildren<ItemContainer>() order is not guaranteed to be index order (and unrealized slots are absent). Concrete scenario: after the first recycle pass, containers[1] is the container for "Item 3", so NullItem_RendersBlankRow asserts non-zero height on a templated row and passes even if the null row is collapsed — the test cannot discriminate the bug it was written for. Resolve the container via ItemsRepeaterControl.TryGetElement(1)/GetElementIndex instead of positional child order. The await Task.Delay(500) above also has no justification — prefer a deterministic wait (AssertEventually/WaitForMainThread) so the test is not timing-dependent on slower Helix agents.

// setting CollectionView.SelectedItem directly. This exercises the
// PlatformSelectionChanged -> UpdateVirtualSingleSelection round-trip, which
// is the path that previously threw/undid selection for a null-item row.
var nullContainer = containers[1];

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[moderate] Logic and Correctness Verification — NullItem_TapDoesNotCrash_SingleSelection drives selection by setting ItemContainer.IsSelected = true directly, which is not the platform tap path this fix targets: a real tap goes through ItemsView.SelectionChanged → PlatformSelectionChanged → UpdateVirtualSingleSelection. Setting IsSelected on the container may not raise the ItemsView.SelectionChanged the handler subscribes to, in which case _ignoreVirtualSelectionChange/UpdateVirtualSingleSelection is never entered and the assertions (SelectedItem is null, container stays selected) hold trivially — including on the unfixed code. Combined with the containers[1] ordering assumption above, this test does not prove the round-trip guard works. Assert against the handler-level round trip (e.g. raise selection via the platform ItemsView.Select(index) API and verify UpdatePlatformSelection was not re-entered).

float nullRowX = itemARect.CenterX();
float nullRowY = (itemARect.Bottom + itemBRect.Top) / 2f;

App.DragCoordinates(nullRowX, nullRowY, itemCRect.CenterX(), itemCRect.CenterY());

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[major] Regression Prevention and Test Coverage — This UI test does not exercise the fixed code path. Gate evidence for this PR shows both tests here fail with the fix applied and leave the order at Item A, null, Item B, Item C; the sibling test DraggingRealItemOntoNullItemRowDoesNotCrashAndReorders, whose drag source is a normal non-null row and therefore does not depend on any null handling, fails identically. That control result indicates App.DragCoordinates does not initiate the WinUI/OLE drag pipeline, so ItemContainer_DragStarting (and hence PerformReorder) is never reached. The PR therefore ships a drag-reorder fix with no executing regression test on any platform. Either drive the reorder through an API-level path that actually raises DragStarting, or replace these with device tests that invoke the handler's drag entry points directly.

App.WaitForElement("ReorderStatusLabel");
var reorderedText = App.WaitForElement("ReorderStatusLabel").GetText();

Assert.That(reorderedText, Is.Not.EqualTo(initialOrder),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[moderate] Regression Prevention and Test Coverage — The assertions (Is.Not.EqualTo(initialOrder), length == 4, Does.Contain("null")) cannot distinguish a correct reorder from a wrong-slot reorder. Concrete scenario: if the drag resolves to the wrong source row (the first null instead of the dragged one, or an adjacent item — the exact failure mode the flat-index changes in MauiItemsView.DragDrop.cs can produce), the resulting order is still 4 items, still contains null, and still differs from the initial order, so the test passes. Assert the exact expected final string (e.g. "Item A, Item B, Item C, null"), which is the only assertion that proves the intended slot moved.

// Default sizing hints for null-data item containers in CV2, based on CV1 behavior.
return new ItemContainer
{
MinHeight = 32,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[moderate] Cross-Platform Behavioral Consistency — MinHeight = 32 / MinWidth = 88 are hard-coded and ignore both the ItemsLayout/ItemSizingStrategy and the surrounding rows' measured size. Concrete scenario: the sample page added by this PR uses HeightRequest="70" rows, so the null row renders at 32px — a visibly different row height than every neighbour, and different from CV1, whose blank row inherits the ListViewItem default rather than a fixed 32/88. Derive the blank container's size from the cached first-item measurement (_firstItemMeasuredSize, already tracked for MeasureFirstItem) or leave it unset and let the layout size it, rather than introducing two magic constants.

// Blank containers created for null regular-data items have no ElementWrapper
// child (and therefore no template key), so they can't go in _recyclePool.
// Pool them separately to avoid reallocating on every scroll over null items.
_nullItemPool.Add(item);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[moderate] Handler Mapper and Property Patterns — Blank containers are pooled without resetting the mutable state that ApplyDragAffordance writes to them (Tag, CanDrag, the DragStarting subscription, and the local Background card brush). That reset lives in ItemsRepeater_ElementClearing, which early-returns when _canReorderItems is false. Concrete scenario: user sets CanReorderItems = false (or the handler updates it) while blank rows are realized — those containers are cleared without the reset, land in _nullItemPool, and are handed back by GetElement still carrying the Fluent card Background, a stale int Tag, CanDrag = true, and a live ItemContainer_DragStarting subscription. The stale Tag alone is enough for ItemContainer_DragStarting to treat the container as hasBinding (line 424) and start a drag on a row the user disabled reordering for. Reset the container state on pooling (or on retrieval) rather than relying on ElementClearing.

// tap, skip the round-trip back to UpdatePlatformSelection. Without this guard,
// tapping a null item causes: WinUI selects null → SelectedItem = null →
// MapSelectedItem → UpdatePlatformSelection → DeselectAll (undoes the selection).
if (handler._ignoreVirtualSelectionChange)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[moderate] Handler Mapper and Property Patterns — Suppressing MapSelectedItem for the entire assignment window drops legitimate selection changes that originate during that window. Concrete scenario: SelectedItem is two-way bound to a view model that coerces/rejects the value (a common "don't allow selecting the placeholder row" pattern). UpdateVirtualSingleSelection sets SelectedItem = null, the VM setter writes back the previous item, the resulting mapper call is swallowed by this guard, and the platform is never told — WinUI keeps the blank row highlighted while CollectionView.SelectedItem is the previous item. Prefer detecting the no-op (compare the incoming value against the current platform selection inside UpdatePlatformSelection) over an unconditional early return, so genuine re-entrant changes still propagate.

// the flag and handler are restored after. Try/finally ensures the flag and event
// handler are always restored even if a BindableProperty callback or user
// PropertyChanged handler throws.
_ignoreVirtualSelectionChange = true;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[moderate] Cross-Platform Behavioral Consistency — The round-trip guard is applied only to the single-selection path. UpdateVirtualMultipleSelection still writes ItemsView.SelectedItems with no equivalent flag, and MapSelectedItems (line 90) calls UpdatePlatformSelection() unconditionally. Concrete scenario: SelectionMode="Multiple" over a source containing a null entry — tapping the blank row runs the same WinUI-selects-null → virtual-write → MapSelectedItems → UpdatePlatformSelection round trip this PR fixes for single selection, and the selection is undone. Neither device test added here covers multiple selection, so the asymmetry is untested.

var newItem = CreateItemContext(e.NewItems[i]!);
// Always create a new context even for null new items — skipping the slot update
// would leave the stale old ItemTemplateContext2 in the flat list (desync).
var newItem = CreateItemContext(e.NewItems[i]);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[moderate] Regression Prevention and Test Coverage — This desync fix (always creating a replacement context so the flat mirror keeps a slot for a null new item) is correct and matches the initial-build path at line 140, which never skipped nulls. It has no test: neither device test in this PR uses IsGrouped, and the UI test page is ungrouped. The specific scenario to cover is a grouped ObservableCollection where an inner group's item is replaced with null (group[i] = null) — before this change the flat list kept the stale ItemTemplateContext2 and every subsequent index-based lookup in MauiItemsView.DragDrop.cs was off. Add a device test asserting the flattened collection count/contents after such a replace; the same test project also exercises the PerformGroupedReorder rewrite flagged at line 884.

MauiBot

This comment was marked as outdated.

@kubaflo

This comment has been minimized.

@MauiBot MauiBot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Expert Review — 8 findings

See inline comments for details.

for (int g = 0; g < groupsList.Count; g++)
{
if (groupsList[g] is not IEnumerable groupItems)
if (groupsList[g] is not IEnumerable groupSrcItems)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[major] Logic and Correctness / CollectionView Shared Models — The new flat-index walk that resolves the drag source does not use the same skip rules as the code that BUILDS the flat list. GroupedItemTemplateCollection2.RebuildFlatList() skips a group with if (group is string || group is not IEnumerable itemsList) continue;, contributing zero flat entries (no header, no items, no footer) for a string group. This loop only skips is not IEnumerable, and string is IEnumerable, so it advances flatSrcPos by 1 (header) + one per character + 1 (footer) for that group. Concrete scenario: grouped ItemsSource = new List<object> { "abc", new ObservableCollection<Item>{...} } with GroupHeaderTemplate set — every flat index after the string group is over-counted by 5, so _draggedSourceIndex maps to the wrong sourceGroupIndex/sourceItemIndex and the reorder removes/inserts a different item than the one dragged (or returns false and silently drops the reorder). The previous value-equality search was immune to this because it never depended on flat positions. Mirror the exact RebuildFlatList skip condition here (and in the target-side loop at line ~916, which now shares the same assumption).

// null items across groups — the Tag is the only per-slot discriminator.
if (container.Child is not ElementWrapper)
{
return container.Tag is int tagIndex && tagIndex == _draggedSourceIndex;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[major] CollectionView Shared Models / Logic and Correctness — For blank (null-item) containers this identifies the drag source by comparing container.Tag to _draggedSourceIndex, but the two values live on different timelines: _draggedSourceIndex is frozen at DragStarting (line 453) while ApplyDragAffordance reassigns container.Tag = index (line 343) on every ElementPrepared, i.e. with the container's CURRENT flat position. The call site at line 326 explicitly exists so that "if a live-reorder recycles a container onto the dragged item's NEW position, hide it" — with an index comparison the hidden slot stays pinned to the ORIGINAL position instead of following the item. Concrete scenario: list [A, null, B, C], start dragging the null row (frozen index 1) and drag downward so a live shuffle re-prepares containers; the container now tagged 1 holds B, so B is set Opacity = 0; IsHitTestVisible = false and _sourceContainer is re-pointed at it, while the actual null source row is only dimmed. The non-null path (line 573) does follow the item, so null rows behave differently from every other row mid-drag.

// tap, skip the round-trip back to UpdatePlatformSelection. Without this guard,
// tapping a null item causes: WinUI selects null → SelectedItem = null →
// MapSelectedItem → UpdatePlatformSelection → DeselectAll (undoes the selection).
if (handler._ignoreVirtualSelectionChange)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[moderate] Handler Mapper and Property Patterns — This early-return suppresses UpdatePlatformSelection for any SelectedItem write that happens synchronously inside the _ignoreVirtualSelectionChange window, not just the handler's own write. ItemsView.SelectedItem = selectedItem (line 341) runs the BindableProperty pipeline synchronously, so a two-way bound view model setter that coerces/rejects the value — e.g. set { if (!CanSelect(value)) { SelectedItem = _previous; return; } ... }, a common "veto selection" pattern — re-enters MapSelectedItem while the flag is still set and is dropped. The WinUI ItemsView then keeps the tapped row selected while CollectionView.SelectedItem holds the coerced value, and the two stay desynced until an unrelated selection change. Before this change the detach of VirtualSelectionChanged alone still let coerced writes reach UpdatePlatformSelection. Consider comparing the incoming value against the value the handler just wrote instead of a blanket flag.

// new ItemContainer on every scroll pass over null items.
if (_nullItemPool.Count > 0)
{
var pooledNullContainer = _nullItemPool[^1];

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[moderate] Handler Mapper / Native Defaults Preservation — Pooled blank containers are handed back with whatever mutable state they carried when recycled: Opacity, IsHitTestVisible, Tag, Background and Translation are only reset by MauiItemsView.ItemsRepeater_ElementClearing/ElementPrepared, and BOTH of those return early when _canReorderItems is false (see MauiItemsView.DragDrop.cs lines 313 and ~370). Concrete scenario: a null row is the drag source (Opacity = 0, IsHitTestVisible = false), the app sets CanReorderItems = false (or the handler remaps it) before the container is recycled — ElementClearing no longer restores it, RecycleElement pools it as-is, and the next null item scrolled into view is rendered invisible and non-hit-testable. Prior to pooling a fresh ItemContainer was allocated every time, so this state could never leak between rows. Reset the drag-mutated properties either when adding to _nullItemPool or when returning from it.

{
if (_draggedItem is null)
// _draggedSourceIndex < 0 means no active drag; _draggedItem may be null for null data rows.
if (_draggedSourceIndex < 0)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[moderate] Logic and Correctness — The flat (non-grouped) path was not given the same index-identity treatment as the grouped path. When the _draggedSourceIndex validation just below fails (index >= itemsList.Count, or the item at that index is no longer null because the collection mutated during the drag), it falls back to oldIndex = IndexOfItem(_draggedItem, itemsList) with _draggedItem == null, and IndexOfItem returns the FIRST null in the list. Concrete scenario: flat ItemsSource = [A, null, B, null, C], drag the second null while a background update inserts an item — the first null is moved instead. This is exactly the null-ambiguity the grouped rewrite (line 863 comment) was introduced to eliminate; the flat path still resolves null sources by value.

{
// Blank container (no ElementWrapper) represents a null data item.
// It matches when the dragged item is also null.
return item is null;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[minor] Logic and Correctness — IsContainerBoundToItem now reports a match for any wrapper-less container whenever the dragged item is null, which is a false identity: all blank containers in the list are indistinguishable under this rule. It is currently unreachable from the only caller (IsContainerBoundToDraggedItem handles wrapper-less containers in the branch above at line 568), so this is dead code that encodes the exact ambiguity the rest of the PR removes. Either delete the branch or make it require the caller-supplied slot index, so the next caller cannot silently match every null row.

App.WaitForElement("ReorderStatusLabel");
var reorderedText = App.WaitForElement("ReorderStatusLabel").GetText();

Assert.That(reorderedText, Is.Not.EqualTo(initialOrder),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[major] Regression Prevention and Test Coverage — These assertions cannot discriminate a correct reorder from a wrong-row reorder: they only check that the order string CHANGED and that "null" is still present with 4 entries. Moving the wrong item (the failure mode this PR's index-identity rewrite exists to prevent) satisfies all three assertions. Assert the exact expected sequence instead. Coverage gaps that follow from the same fixture: (a) only ONE null item is present, so the multiple-null ambiguity that motivated _draggedSourceIndex/Tag identity is never exercised; (b) there is no grouped test at all, yet PerformGroupedReorder's source lookup was rewritten from value equality to flat-index walking — the highest-risk change in the PR ships untested; (c) CanMixGroups/group header+footer flat offsets are untested.

var nullContainer = containers[1];
var exception = await Record.ExceptionAsync(async () =>
{
nullContainer.IsSelected = true;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[moderate] Regression Prevention and Test Coverage — This test identifies the null row purely as containers[1] from GetChildren<ItemContainer>(), which depends on visual-tree enumeration order rather than the data index, and it sequences with Task.Delay(500)/Task.Delay(100) instead of a deterministic wait — both make the assertion prone to passing (or flaking) for the wrong container. It also never covers the case the new MapSelectedItem guard is aimed at when a second null item exists, so it cannot detect selection landing on the wrong null row. Prefer asserting the container via its data index / bound context and use the existing deterministic wait helpers.

@MauiBot MauiBot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

AI Review Summary

@SuthiYuvaraj — new AI review results are available based on commit f5716e2.

Gate Failed Confidence Medium Platform Windows


🗂️ Review Sessions — click to expand
🚦 Gate — Test Before & After Fix

Gate Result: ❌ FAILED

Platform: WINDOWS · Base: net11.0 · Merge base: 21ea9c91

🩺 The PR's test does not compile — the build error is in one of the PR's own test files, which the gate never reverts, so it fails identically without and with the fix. This is NOT a pre-existing/environment failure — the PR must fix its test (e.g. an ambiguous using / type collision). Investigate the PR's test code.

D:\a\1\s\src\Controls\tests\DeviceTests\Elements\CollectionView\CollectionViewTests.Windows.cs(46,21): error CS0104: 'SelectionMode' is an ambiguous reference between 'Microsoft.Maui.Controls.Selectio...

Test Without Fix (expect FAIL) With Fix (expect PASS)
📱 CollectionViewTests (NullItem_RendersBlankRow, NullItem_TapDoesNotCrash_SingleSelection) Category=CollectionView 🛠️ BUILD ERROR 🛠️ BUILD ERROR
🖥️ CollectionViewNullItemDragReorder CollectionViewNullItemDragReorder ✅ FAIL — 349s ❌ FAIL — 819s
🔴 Without fix — 📱 CollectionViewTests (NullItem_RendersBlankRow, NullItem_TapDoesNotCrash_SingleSelection): 🛠️ BUILD ERROR · 316s

Error-relevant lines (filtered from the build log):

D:\a\1\s\src\Controls\tests\DeviceTests\Elements\CollectionView\CollectionViewTests.Windows.cs(174,12): error CS0104: 'ColumnDefinition' is an ambiguous reference between 'Microsoft.Maui.Controls.ColumnDefinition' and 'Microsoft.UI.Xaml.Controls.ColumnDefinition' [D:\a\1\s\src\Controls\tests\DeviceTests\Controls.DeviceTests.csproj::TargetFramework=net11.0-windows10.0.19041.0]
D:\a\1\s\src\Controls\tests\DeviceTests\Elements\CollectionView\CollectionViewTests.Windows.cs(175,12): error CS0104: 'ColumnDefinition' is an ambiguous reference between 'Microsoft.Maui.Controls.ColumnDefinition' and 'Microsoft.UI.Xaml.Controls.ColumnDefinition' [D:\a\1\s\src\Controls\tests\DeviceTests\Controls.DeviceTests.csproj::TargetFramework=net11.0-windows10.0.19041.0]
D:\a\1\s\src\Controls\tests\DeviceTests\Elements\CollectionView\CollectionViewTests.Windows.cs(176,12): error CS0104: 'ColumnDefinition' is an ambiguous reference between 'Microsoft.Maui.Controls.ColumnDefinition' and 'Microsoft.UI.Xaml.Controls.ColumnDefinition' [D:\a\1\s\src\Controls\tests\DeviceTests\Controls.DeviceTests.csproj::TargetFramework=net11.0-windows10.0.19041.0]
D:\a\1\s\src\Controls\tests\DeviceTests\Elements\CollectionView\CollectionViewTests.Windows.cs(177,12): error CS0104: 'ColumnDefinition' is an ambiguous reference between 'Microsoft.Maui.Controls.ColumnDefinition' and 'Microsoft.UI.Xaml.Controls.ColumnDefinition' [D:\a\1\s\src\Controls\tests\DeviceTests\Controls.DeviceTests.csproj::TargetFramework=net11.0-windows10.0.19041.0]
D:\a\1\s\src\Controls\tests\DeviceTests\Elements\CollectionView\CollectionViewTests.Windows.cs(178,12): error CS0104: 'ColumnDefinition' is an ambiguous reference between 'Microsoft.Maui.Controls.ColumnDefinition' and 'Microsoft.UI.Xaml.Controls.ColumnDefinition' [D:\a\1\s\src\Controls\tests\DeviceTests\Controls.DeviceTests.csproj::TargetFramework=net11.0-windows10.0.19041.0]
D:\a\1\s\src\Controls\tests\DeviceTests\Elements\CollectionView\CollectionViewTests.Windows.cs(186,7): error CS0104: 'Grid' is an ambiguous reference between 'Microsoft.Maui.Controls.Grid' and 'Microsoft.UI.Xaml.Controls.Grid' [D:\a\1\s\src\Controls\tests\DeviceTests\Controls.DeviceTests.csproj::TargetFramework=net11.0-windows10.0.19041.0]
D:\a\1\s\src\Controls\tests\DeviceTests\Elements\CollectionView\CollectionViewTests.Windows.cs(364,21): error CS0104: 'Grid' is an ambiguous reference between 'Microsoft.Maui.Controls.Grid' and 'Microsoft.UI.Xaml.Controls.Grid' [D:\a\1\s\src\Controls\tests\DeviceTests\Controls.DeviceTests.csproj::TargetFramework=net11.0-windows10.0.19041.0]
D:\a\1\s\src\Controls\tests\DeviceTests\Elements\CollectionView\CollectionViewTests.Windows.cs(435,13): error CS1061: 'MauiAppBuilder' does not contain a definition for 'ConfigureMauiHandlers' and no accessible extension method 'ConfigureMauiHandlers' accepting a first argument of type 'MauiAppBuilder' could be found (are you missing a using directive or an assembly reference?) [D:\a\1\s\src\Controls\tests\DeviceTests\Controls.DeviceTests.csproj::TargetFramework=net11.0-windows10.0.19041.0]
D:\a\1\s\src\Controls\tests\DeviceTests\Elements\CollectionView\CollectionViewTests.Windows.cs(479,13): error CS1061: 'MauiAppBuilder' does not contain a definition for 'ConfigureMauiHandlers' and no accessible extension method 'ConfigureMauiHandlers' accepting a first argument of type 'MauiAppBuilder' could be found (are you missing a using directive or an assembly reference?) [D:\a\1\s\src\Controls\tests\DeviceTests\Controls.DeviceTests.csproj::TargetFramework=net11.0-windows10.0.19041.0]
D:\a\1\s\src\Controls\tests\DeviceTests\Elements\CollectionView\CollectionViewTests.Windows.cs(498,21): error CS0104: 'SelectionMode' is an ambiguous reference between 'Microsoft.Maui.Controls.SelectionMode' and 'Microsoft.UI.Xaml.Controls.SelectionMode' [D:\a\1\s\src\Controls\tests\DeviceTests\Controls.DeviceTests.csproj::TargetFramework=net11.0-windows10.0.19041.0]
Build FAILED.
🟢 With fix — 📱 CollectionViewTests (NullItem_RendersBlankRow, NullItem_TapDoesNotCrash_SingleSelection): 🛠️ BUILD ERROR · 121s

Error-relevant lines (filtered from the build log):

D:\a\1\s\src\Controls\tests\DeviceTests\Elements\CollectionView\CollectionViewTests.Windows.cs(174,12): error CS0104: 'ColumnDefinition' is an ambiguous reference between 'Microsoft.Maui.Controls.ColumnDefinition' and 'Microsoft.UI.Xaml.Controls.ColumnDefinition' [D:\a\1\s\src\Controls\tests\DeviceTests\Controls.DeviceTests.csproj::TargetFramework=net11.0-windows10.0.19041.0]
D:\a\1\s\src\Controls\tests\DeviceTests\Elements\CollectionView\CollectionViewTests.Windows.cs(175,12): error CS0104: 'ColumnDefinition' is an ambiguous reference between 'Microsoft.Maui.Controls.ColumnDefinition' and 'Microsoft.UI.Xaml.Controls.ColumnDefinition' [D:\a\1\s\src\Controls\tests\DeviceTests\Controls.DeviceTests.csproj::TargetFramework=net11.0-windows10.0.19041.0]
D:\a\1\s\src\Controls\tests\DeviceTests\Elements\CollectionView\CollectionViewTests.Windows.cs(176,12): error CS0104: 'ColumnDefinition' is an ambiguous reference between 'Microsoft.Maui.Controls.ColumnDefinition' and 'Microsoft.UI.Xaml.Controls.ColumnDefinition' [D:\a\1\s\src\Controls\tests\DeviceTests\Controls.DeviceTests.csproj::TargetFramework=net11.0-windows10.0.19041.0]
D:\a\1\s\src\Controls\tests\DeviceTests\Elements\CollectionView\CollectionViewTests.Windows.cs(177,12): error CS0104: 'ColumnDefinition' is an ambiguous reference between 'Microsoft.Maui.Controls.ColumnDefinition' and 'Microsoft.UI.Xaml.Controls.ColumnDefinition' [D:\a\1\s\src\Controls\tests\DeviceTests\Controls.DeviceTests.csproj::TargetFramework=net11.0-windows10.0.19041.0]
D:\a\1\s\src\Controls\tests\DeviceTests\Elements\CollectionView\CollectionViewTests.Windows.cs(178,12): error CS0104: 'ColumnDefinition' is an ambiguous reference between 'Microsoft.Maui.Controls.ColumnDefinition' and 'Microsoft.UI.Xaml.Controls.ColumnDefinition' [D:\a\1\s\src\Controls\tests\DeviceTests\Controls.DeviceTests.csproj::TargetFramework=net11.0-windows10.0.19041.0]
D:\a\1\s\src\Controls\tests\DeviceTests\Elements\CollectionView\CollectionViewTests.Windows.cs(186,7): error CS0104: 'Grid' is an ambiguous reference between 'Microsoft.Maui.Controls.Grid' and 'Microsoft.UI.Xaml.Controls.Grid' [D:\a\1\s\src\Controls\tests\DeviceTests\Controls.DeviceTests.csproj::TargetFramework=net11.0-windows10.0.19041.0]
D:\a\1\s\src\Controls\tests\DeviceTests\Elements\CollectionView\CollectionViewTests.Windows.cs(364,21): error CS0104: 'Grid' is an ambiguous reference between 'Microsoft.Maui.Controls.Grid' and 'Microsoft.UI.Xaml.Controls.Grid' [D:\a\1\s\src\Controls\tests\DeviceTests\Controls.DeviceTests.csproj::TargetFramework=net11.0-windows10.0.19041.0]
D:\a\1\s\src\Controls\tests\DeviceTests\Elements\CollectionView\CollectionViewTests.Windows.cs(435,13): error CS1061: 'MauiAppBuilder' does not contain a definition for 'ConfigureMauiHandlers' and no accessible extension method 'ConfigureMauiHandlers' accepting a first argument of type 'MauiAppBuilder' could be found (are you missing a using directive or an assembly reference?) [D:\a\1\s\src\Controls\tests\DeviceTests\Controls.DeviceTests.csproj::TargetFramework=net11.0-windows10.0.19041.0]
D:\a\1\s\src\Controls\tests\DeviceTests\Elements\CollectionView\CollectionViewTests.Windows.cs(479,13): error CS1061: 'MauiAppBuilder' does not contain a definition for 'ConfigureMauiHandlers' and no accessible extension method 'ConfigureMauiHandlers' accepting a first argument of type 'MauiAppBuilder' could be found (are you missing a using directive or an assembly reference?) [D:\a\1\s\src\Controls\tests\DeviceTests\Controls.DeviceTests.csproj::TargetFramework=net11.0-windows10.0.19041.0]
D:\a\1\s\src\Controls\tests\DeviceTests\Elements\CollectionView\CollectionViewTests.Windows.cs(498,21): error CS0104: 'SelectionMode' is an ambiguous reference between 'Microsoft.Maui.Controls.SelectionMode' and 'Microsoft.UI.Xaml.Controls.SelectionMode' [D:\a\1\s\src\Controls\tests\DeviceTests\Controls.DeviceTests.csproj::TargetFramework=net11.0-windows10.0.19041.0]
Build FAILED.
🔴 Without fix — 🖥️ CollectionViewNullItemDragReorder: FAIL ✅ · 349s

Error-relevant lines (filtered from the build log):

     at Microsoft.Maui.TestCases.Tests.Issues.CollectionViewNullItemDragReorder.DraggingNullItemRowDoesNotCrashAndReorders() in /_/src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/CollectionViewNullItemDragReorder.cs:line 39
     at Microsoft.Maui.TestCases.Tests.Issues.CollectionViewNullItemDragReorder.DraggingRealItemOntoNullItemRowDoesNotCrashAndReorders() in /_/src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/CollectionViewNullItemDragReorder.cs:line 73
🟢 With fix — 🖥️ CollectionViewNullItemDragReorder: FAIL ❌ · 819s

Error-relevant lines (filtered from the build log):

     at Microsoft.Maui.TestCases.Tests.Issues.CollectionViewNullItemDragReorder.DraggingNullItemRowDoesNotCrashAndReorders() in /_/src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/CollectionViewNullItemDragReorder.cs:line 39
     at Microsoft.Maui.TestCases.Tests.Issues.CollectionViewNullItemDragReorder.DraggingRealItemOntoNullItemRowDoesNotCrashAndReorders() in /_/src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/CollectionViewNullItemDragReorder.cs:line 73

⚠️ Failure Details

  • 🛠️ CollectionViewTests (NullItem_RendersBlankRow, NullItem_TapDoesNotCrash_SingleSelection) without fix: build failed before tests could run
    • D:\a\1\s\src\Controls\tests\DeviceTests\Elements\CollectionView\CollectionViewTests.Windows.cs(46,21): error CS0104: 'SelectionMode' is an ambiguous reference between 'Microsoft.Maui.Controls.Selectio...
  • 🛠️ CollectionViewTests (NullItem_RendersBlankRow, NullItem_TapDoesNotCrash_SingleSelection) with fix: build failed (fix does not compile)
    • D:\a\1\s\src\Controls\tests\DeviceTests\Elements\CollectionView\CollectionViewTests.Windows.cs(46,21): error CS0104: 'SelectionMode' is an ambiguous reference between 'Microsoft.Maui.Controls.Selectio...
  • ❌ CollectionViewNullItemDragReorder FAILED with fix (should pass)
    • DraggingNullItemRowDoesNotCrashAndReorders [4 s]; DraggingRealItemOntoNullItemRowDoesNotCrashAndReorders [4 s]
    • Dragging the null-item row should trigger ReorderCompleted and change the item order. Assert.That(reorderedText, Is.Not.EqualTo(initialOrder)) Expected: not equal to "Item A, null, Item B, Item C"...; Dropping an item onto the null-item row should trigger ReorderCompleted and change the item ord...
📁 Fix files reverted (4 files)
  • src/Controls/src/Core/Handlers/Items2/CollectionViewHandler2.Windows.cs
  • src/Controls/src/Core/Handlers/Items2/Windows/GroupedItemTemplateCollection2.cs
  • src/Controls/src/Core/Handlers/Items2/Windows/ItemFactory.cs
  • src/Controls/src/Core/Handlers/Items2/Windows/MauiItemsView.DragDrop.cs

📋 Pre-Flight — Context & Validation

PR #36170 Pre-Flight

Context

  • Title: [WinUI][CV2] Fix for Null Item Handling - follow-ups from CollectionView2 Windows handler (#34600)
  • Base / head: net11.0 / Fix-nullItemCV2; local review commit 6ff3400039d2bb63e3a102cb02c32ad750ed8d46
  • Issue: #36068 tracks null source-item handling in the Windows CollectionView2 handler.
  • Platform: Windows
  • Gate: Failed. The two device tests do not compile because the PR added using Microsoft.UI.Xaml.Controls, creating ambiguous MAUI/WinUI references and omitting the extension namespace needed by ConfigureMauiHandlers. The UI tests fail both with and without the PR fix because neither drag changes the source order.

Existing Fix Inspected

The committed PR diff changes four production files and adds device/UI tests:

  1. CollectionViewHandler2.Windows.cs suppresses the mapper round-trip while WinUI propagates a selected null item.
  2. GroupedItemTemplateCollection2.cs creates replacement contexts for null values instead of leaving the flattened grouped mirror stale.
  3. ItemFactory.cs renders null data as pooled blank ItemContainer instances.
  4. MauiItemsView.DragDrop.cs treats _draggedSourceIndex as the active-drag sentinel, identifies null rows by repeater index/Tag, and uses the flat index for grouped reorder.

The approach is broad and stateful. In particular, the blank-container path removes the normal ElementWrapper, then compensates throughout drag/drop using Tag; the gate shows that this still does not produce a completed reorder for either null-origin or null-target drag.

Changed Tests and Bounded Validation

  • Primary UI test: pwsh .github/scripts/BuildAndRunHostApp.ps1 -Platform windows -TestFilter "CollectionViewNullItemDragReorder"
    • DraggingNullItemRowDoesNotCrashAndReorders
    • DraggingRealItemOntoNullItemRowDoesNotCrashAndReorders
  • Mandatory device regression test: pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project Controls -Platform windows -TestFilter "Category=CollectionView"
    • Added tests: NullItem_RendersBlankRow and NullItem_TapDoesNotCrash_SingleSelection
    • Known gate blocker: the PR's device-test source currently has compile errors outside the try-fix modification allow-list. Record this honestly; do not edit test files.

Each candidate gets one implementation/test pass and at most one focused correction/retest. Do not run the gate or any full suite.

Try-Fix Boundaries

  • Invoke the try-fix skill once per candidate.
  • The only production target files are:
    • src/Controls/src/Core/Handlers/Items2/CollectionViewHandler2.Windows.cs
    • src/Controls/src/Core/Handlers/Items2/Windows/GroupedItemTemplateCollection2.cs
    • src/Controls/src/Core/Handlers/Items2/Windows/ItemFactory.cs
    • src/Controls/src/Core/Handlers/Items2/Windows/MauiItemsView.DragDrop.cs
  • Obey .github/.baseline-state.json after EstablishBrokenBaseline.ps1; restore only with pwsh .github/scripts/EstablishBrokenBaseline.ps1 -Restore.
  • Preserve all unrelated tracked and untracked worktree changes.
  • The repository's handler-detection guidance predates the Windows Items2 implementation; the actual net11.0 code and PR tests explicitly register and execute CollectionViewHandler2 on Windows.

🔬 Code Review — Deep Analysis

Expert Evaluation: REQUEST CHANGES

Verdict: NEEDS_CHANGES
Confidence: medium

The submitted fix correctly repairs grouped Replace notifications by preserving one ItemTemplateContext2 per source slot, and its try/finally restores the selection event subscription and suppression flag. However, the broader null-item identity changes introduce concrete wrong-row and stale-container failure modes, while the trusted Gate failed: both drag UI tests leave the source order unchanged and the new Windows device tests do not compile.

Blocking findings

  1. PerformGroupedReorder walks string groups even though GroupedItemTemplateCollection2.RebuildFlatList skips them. Its computed flat offset can therefore resolve a dragged index to the wrong group or item.
  2. Null-row source matching compares the frozen _draggedSourceIndex with a Tag rewritten to the container's current position during live reorder. After containers move, an unrelated row can become invisible and non-hit-testable while the actual dragged null row is merely dimmed.
  3. The flat reorder fallback still resolves a null item by value and can move the first null rather than the dragged null when the source changes during a drag.
  4. _ignoreVirtualSelectionChange suppresses every synchronous re-entrant SelectedItem mapping, including a bound view model that coerces or rejects the handler's value, leaving virtual and WinUI selection out of sync.
  5. _nullItemPool reuses childless containers without resetting drag-mutated state. If reordering is disabled before clearing, an invisible/non-hit-testable container can be returned for another null row.

Test findings

The UI assertions accept any changed order rather than the exact expected sequence, use only one null item, and do not cover grouped reorder or header/footer offsets. The device selection test depends on visual-tree child ordering and fixed delays. These tests do not protect the identity mechanisms introduced by the fix, and the Gate could not execute the device tests because of PR-authored compile errors.

Raw added-line findings are recorded in CustomAgentLogsTmp/PRState/36170/PRAgent/inline-findings.json.


🛠️ Try-Fix — Analysis & Comparison

PR #36170 Try-Fix Aggregate

Candidate 1 — Claude Opus 5

Result: Blocked before implementation.

Designed approach: Use each slot's non-null, reference-unique ItemTemplateContext2 from the flat template mirror as the identity for selection and drag/drop. Keep null items on the normal templated ElementWrapper path, make grouped Replace preserve one context per slot, and convert the slot identity to a source position only at mutation time.

Prior approach avoided: The PR retains raw-item value identity and compensates for null with childless blank containers, _draggedSourceIndex sentinel semantics, Tag/GetElementIndex lookups, grouped flat-index reconstruction, and a mapper suppression flag. That approach leaves multiple flat/source index conversions and changes null-row geometry.

Mechanism-level difference: A distinct context object is intrinsically unambiguous for null and duplicate values, eliminating the need for out-of-band identity. Retaining the normal wrapper also preserves the template's 70px row geometry and hit target. Candidate 1 identified a falsifiable explanation for both UI failures: the PR replaces that row with a childless container having MinHeight = 32; the tests' midpoint coordinate can then fall in inter-row margin, leaving _insertionIndex = -1 and causing Drop to clean up without reordering.

Diff / files changed: None; the candidate diff is explicitly empty.

Blocker: The mandatory EstablishBrokenBaseline.ps1 aborted on 43 pre-existing unrelated tracked changes under .github/scripts, .github/skills, and eng/scripts. No .github/.baseline-state.json was created, so the skill correctly prohibited edits that could not be restored. The unrelated changes include harness-owned test scripts and were left untouched.

Tests: Not run because no candidate code was applied.

  • Primary UI: pwsh .github/scripts/BuildAndRunHostApp.ps1 -Platform windows -TestFilter "CollectionViewNullItemDragReorder" — not run.
  • Mandatory device regression: pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project Controls -Platform windows -TestFilter "Category=CollectionView" — not run.

Self-review: 0 findings; empty final diff.

Restoration: pwsh .github/scripts/EstablishBrokenBaseline.ps1 -Restore completed with the accepted no-state result (Restored=False, No baseline state found). Target files remained clean and the 43 unrelated tracked changes were unchanged.

Full narrative: CustomAgentLogsTmp/PRState/36170/PRAgent/try-fix-1/content.md.

Candidate 2 — GPT-5.6 Sol

Result: Blocked before implementation.

Designed approach: Treat the residual UI failure as a WinUI drag-lifecycle ordering race. ItemContainer.DropCompleted may clear _draggedSourceIndex and _insertionIndex before or reentrantly around routed ScrollViewer.Drop. Defer cancel/outside cleanup by one DispatcherQueue turn and protect it with a monotonically increasing drag-generation token; routed Drop marks the generation handled and consumes the captured indices first.

Contrast with the PR and candidate 1: This candidate leaves the PR's item/index resolution and container geometry intact. It does not use candidate 1's per-slot ItemTemplateContext2 identity or normal-wrapper geometry hypothesis. Its causal chain is event ordering, premature state reset, then the inactive-drag guard aborting before source mutation.

Mechanism-level difference: Generation-checked deferred cleanup changes state lifetime rather than slot identity. A valid routed Drop gets first use of the already-resolved source and insertion indices, while cancel, ESC, and outside-drop paths still clean a matching active generation on the next dispatcher turn. The falsifiable signal is ScrollViewer_Drop observing reset indices after a successful DragOver.

Diff / files changed: None; the candidate diff is explicitly empty.

Blocker: The mandatory baseline command rejected the same 43 pre-existing unrelated tracked changes. It created no .github/.baseline-state.json, so no safely restorable implementation pass was possible. Candidate 2 did not bypass the guard or alter the existing worktree.

Tests: Not run because no candidate code was applied.

  • Primary UI: pwsh .github/scripts/BuildAndRunHostApp.ps1 -Platform windows -TestFilter "CollectionViewNullItemDragReorder" — not run.
  • Mandatory device regression: pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project Controls -Platform windows -TestFilter "Category=CollectionView" — not run.

Self-review: 0 findings; empty final diff.

Restoration: pwsh .github/scripts/EstablishBrokenBaseline.ps1 -Restore completed with exit code 0 and the accepted no-state result (Restored=False, No baseline state found). The 43-entry tracked status was unchanged and all four target files remained clean.

Full narrative: CustomAgentLogsTmp/PRState/36170/PRAgent/try-fix-2/content.md.

Aggregate Outcome

Two candidates were attempted in the required order and no further agents were launched. Both produced distinct, bounded designs but were blocked before code changes by the same mandatory baseline guard. No candidate can claim Pass or Fail because neither implementation nor requested test command ran.


📝 PR Finalize — Recommended Title & Description

Assessment: ✏️ Recommend updating — the current description inaccurately claims container-identity selection logic and substantially understates the submitted null-container, selection-suppression, drag/reorder, and test changes.

Recommended title

[Windows] CollectionView2: Fix null-item selection, replacement, and drag reorder

Recommended description

### Issue Description

CollectionView2 on Windows does not consistently handle `null` entries in selection, grouped replacement, rendering, and drag-and-drop reorder paths.

### Root Cause

**Null-item selection**

WinUI represents a selected null-data row with an `ItemTemplateContext2` whose `Item` is `null`, while MAUI's `SelectedItem` is also `null`. The mapper round-trip therefore treated the selected null value as no selection and called `DeselectAll`. Selection visual-state updates also bypassed `VisualElement.IsItemSelected`.

**Grouped null replacement**

When a grouped source raised an `INotifyCollectionChanged.Replace` event with a null new item, `HandleGroupItemsReplace` skipped that slot. The flattened `GroupedItemTemplateCollection2` then retained the old context and diverged from the source.

**Null-item realization and reorder**

Null entries had no dedicated `ItemContainer` realization/recycling path. Drag state and item lookup also used `_draggedItem is null` as an inactive-drag signal and relied on value equality, which cannot distinguish a valid null row from no item or distinguish multiple null slots.

### Description of Change

- `CollectionViewHandler2.Windows.cs`
  - Uses `VisualElement.IsItemSelected` when synchronizing item visual states.
  - Suppresses the `MapSelectedItem` round-trip while platform single-selection writes `SelectedItem`, restoring the flag and `SelectionChanged` subscription in `finally`.
- `GroupedItemTemplateCollection2.cs`
  - Accepts nullable items in `CreateItemContext`.
  - Always creates and installs a replacement `ItemTemplateContext2`, including for null new items.
- `ItemFactory.cs`
  - Realizes regular null entries as childless blank `ItemContainer` rows.
  - Adds a dedicated recycle pool for those containers and clears it during cleanup.
- `MauiItemsView.DragDrop.cs`
  - Uses `_draggedSourceIndex` as the active-drag sentinel so a null data item can be dragged.
  - Uses repeater indices and container `Tag` values to resolve null rows.
  - Updates flat and grouped reorder paths, grouped flat-index mapping, container index refresh, and drag cleanup for null items.
- Adds Windows device and UI coverage for null-row realization, platform-side single selection, dragging a null row, and dropping a real item onto a null row.

### Issues Fixed

Fixes #36068

### Tested the behaviour in the following platforms

- [ ] Android
- [x] Windows
- [ ] iOS
- [ ] Mac

### Output Screenshot

Before Issue Fix | After Issue Fix
|---|---|
| <video width="100" height="100" alt="Before Fix" src="https://github.com/user-attachments/assets/a4fc0c94-76e0-436e-bdea-6291a36b50c2"> | <video width="100" height="100" alt="After Fix" src="https://github.com/user-attachments/assets/c3dd5c3c-e798-4b3b-813c-b4c51e577d07"> |

🏁 Report — Final Recommendation

⚠️ Final Recommendation: REQUEST CHANGES

The raw PR is the least-bad materialized candidate, but it is not approvable. The trusted Gate failed, the expert review found concrete wrong-row and selection-desynchronization defects, and no candidate passed the required regression validation.

Candidate comparison

Rank Candidate Implementation Validation Assessment
1 pr Submitted production and test diff Failed. Both drag UI tests left the order unchanged; the PR-authored device tests did not compile. Only candidate whose submitted production code compiled far enough to run the focused UI tests. It retains blocking expert findings and does not fix the reported drag behavior.
2 pr-plus-reviewer One consolidated patch addressing slot identity, grouped offsets, selection re-entry, null-container geometry, and test compilation/assertions Failed to compile in both required commands: MauiItemsView.DragDrop.cs(1334,1336) references an undefined repeater local. No tests ran, and the contract prohibited repair/retest. The design addresses the expert findings more directly than the PR, but a non-compiling candidate cannot win.
3 try-fix-1 Designed per-slot ItemTemplateContext2 identity and normal templated null rows Blocked; not run. No implementation or candidate diff exists. Strongest alternative design, and it anticipated the PR's null-row geometry/identity risks, but it is only a hypothesis.
4 try-fix-2 Designed generation-checked deferred DropCompleted cleanup Blocked; not run. No implementation or candidate diff exists. Plausible event-ordering hypothesis, but unsupported by a diff or empirical result and less directly responsive to the expert findings.

Expert findings against the submitted PR

  • The grouped source/target flat-index walks disagree with GroupedItemTemplateCollection2.RebuildFlatList for string groups and can move the wrong item.
  • Null-row live-reorder matching compares a frozen source index with a re-tagged current container index, potentially hiding an unrelated row.
  • Flat reorder can fall back from a displaced null slot to the first null in the source.
  • _ignoreVirtualSelectionChange can swallow a synchronous view-model coercion and leave WinUI and MAUI selection desynchronized.
  • Pooled childless null containers can retain drag-mutated visual state.
  • UI assertions do not discriminate correct reorder from wrong-row reorder, and grouped/multiple-null coverage is absent.

Winner

pr wins only because every alternative is either non-compiling or unimplemented. This is a comparative winner, not an approval: the submitted change requires a corrected, compiling implementation and passing focused Windows validation before merge.


📱 UI Tests — CollectionView

Detected UI test categories: CollectionView

[!WARNING]
No UI test results were produced for the detected categories. The platform-pool run
returned no results — most often because the PR build failed (see the Gate section) or
the deep UI test stage was skipped. Fix the build/gate issues and push again; the review
re-runs on new commits (a maintainer can also re-run it).


🧭 Next Steps — review latest findings

No alternative fix was selected for this run. Review the session findings and CI results before merging.

@kubaflo

kubaflo commented Aug 24, 2026

Copy link
Copy Markdown
Contributor

Could you please create a new PR with suggestions - it will be easier to track

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

Labels

area-controls-collectionview CollectionView, CarouselView, IndicatorView community ✨ Community Contribution partner/syncfusion Issues / PR's with Syncfusion collaboration platform/windows s/agent-changes-requested AI agent recommends changes - found a better alternative or issues s/agent-fix-pr-picked AI could not beat the PR fix - PR is the best among all candidates s/agent-gate-failed AI could not verify tests catch the bug s/agent-reviewed PR was reviewed by AI agent workflow (full 4-phase review)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants