Skip to content

Select a Picker SelectedItem that was set before its ItemsSource - #39175

Merged
kubaflo merged 7 commits into
dotnet:inflight/currentfrom
MykhailoDav:fix-30644-picker-selecteditem-before-itemssource
Oct 6, 2026
Merged

kubaflo merged 7 commits into
dotnet:inflight/currentfrom
MykhailoDav:fix-30644-picker-selecteditem-before-itemssource

Conversation

@MykhailoDav

@MykhailoDav MykhailoDav commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Description of Change

A Picker loses its selection when SelectedItem is set before ItemsSource, which is what happens when SelectedItem comes first in XAML:

<Picker SelectedItem="{Binding Selected}" ItemsSource="{Binding Values}" />  <!-- nothing selected -->
<Picker ItemsSource="{Binding Values}" SelectedItem="{Binding Selected}" />  <!-- works -->

Because SelectedItem is TwoWay, the lost selection is also written back: Selected in the view model becomes null.

Root cause

  1. Setting SelectedItem calls UpdateSelectedIndex, which looks the item up in the still-empty Items and leaves SelectedIndex at -1.
  2. Setting ItemsSource calls ResetItems, which calls ClampSelectedIndex(SelectedIndex), i.e. ClampSelectedIndex(-1).
  3. ClampSelectedIndex(-1) calls UpdateSelectedItem(-1), which sets SelectedItem to null.

Fix

In ResetItems, when there's no valid SelectedIndex but SelectedItem is set, look the item up in the new ItemsSource. This is how ResyncItemsAndReconcileSelection already reconciles the selection after a collection reset, and it is the SelectedItem counterpart of #35629, which made a SelectedIndex set before the items order-independent.

Unchanged:

  • A valid SelectedIndex is still used as before. ResetItems also runs when the handler connects and when ItemDisplayBinding changes.
  • A SelectedItem that isn't in ItemsSource is still cleared.
  • SelectedIndexChanged is raised once, the same as when ItemsSource is set first and SelectedItem second.

Picker.cs is identical on net11.0, so the issue is there too.

Tests

  • PickerTests (Core.UnitTests):
    • SelectedItemSetBeforeItemsSourceIsSelected
    • SelectedItemBoundBeforeItemsSourceKeepsBoundValue (bindings applied in that order; the bound value is kept)
    • SelectedItemNotInItemsSourceSetBeforeItemsSourceIsCleared (behavior unchanged)
  • Maui30644 (Xaml.UnitTests, Runtime/XamlC/SourceGen): the reporter's page, with one picker in each attribute order and compiled bindings.
Without fix With fix
PickerTests 60 passed, 2 failed 62 passed
Maui30644 3 failed (SelectedIndex is -1 for every inflator) 3 passed

With the fix, the full suites pass: Controls.Core.UnitTests 5721 passed / 30 skipped, and Controls.Xaml.UnitTests 2013 passed / 8 skipped.

Issues Fixed

Fixes #30644

kubaflo and others added 7 commits October 5, 2026 00:25
<!-- Please let the below note in for people that find this PR -->
> [!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](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!

<!--
!!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING
MAIN. !!!!!!!
-->

### Description of Change

<!-- Enter description of the fix in this section -->

Make the `Issue24284.FlyoutHeaderAdaptsToMinimumHeight` reference
visible while the fixture's flyout is initially open. On main,
`HeightReferenceLabel` is on Page 1 behind that flyout. Move the
existing unchanged `Label` (`HeightRequest="30"`,
`AutomationId="HeightReferenceLabel"`, `Text="Hello, World!"`) into
`Shell.FlyoutFooter`, leaving Page 1 empty.

Main already compares measured reference and header heights. Preserve
the exact strict contract `Math.Abs(headerLabel.Height -
heightReferenceLabel.Height) < 0.2`; this does not replace a hardcoded
30 comparison or loosen the tolerance. Add a positive-reference-height
assertion and measured-height failure diagnostics.

Only the fixture XAML and its test change. The constructor remains
untouched: `FlyoutIsPresented = true`, header text `Flyout Header`,
`MinimumHeightRequest = 30`, and `CollapseOnScroll` behavior are
preserved, as is all-platform scope. No product fixes, retries, timeout
changes, snapshots, flyout opening/closing workarounds, or shared
harness edits.

This is a clean main-based replacement for closed predecessor
[dotnet#39122](dotnet#39122), not a retarget or a
merge of candidate history. Its starting main SHA is
`32583cd272cf1ac485243fd13d322bb13f147914`.

**Static validation (all passed):**
- `dotnet format whitespace --folder --include
src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue24284.cs` -
passed (exit 0).
- `dotnet format whitespace --folder --include
src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue24284.cs
--verify-no-changes` - passed (exit 0).
- `xmllint --noout
src/Controls/tests/TestCases.HostApp/Issues/Issue24284.xaml` - passed
(exit 0); XML well-formedness only, not XAML compilation.
- `git diff --check` - passed (exit 0).

**Validation limitations:** No local native builds, XAML compilation,
UI/device tests, simulator/emulator or Appium execution were performed.
Actual main-based UI execution and native/XAML compilation remain
unverified pending CI.

**Historical candidate evidence only (not main validation):** On
predecessor dotnet#39122, [UI build
1622631](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1622631)
passed the Mac target on both original and subsequent executions (log
5497, lines 719/2422). The contemporaneous
[dotnet#39123](dotnet#39123) on the same
candidate base without this footer fix failed Mac both times ([UI build
1622632](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1622632),
log 5497, lines 720/2422). Fixed Windows, iOSlatest and AndroidMono
targets also passed there; AndroidCoreCLR and the full UI run were still
incomplete. This supports the fixture approach but does not establish
results for this main-based replacement.

### Issues Fixed

<!-- Please make sure that there is a bug logged for the issue being
fixed. The bug should describe the problem and how to reproduce it. -->

Refs dotnet#24284 (fixture reliability only; no claim to fix or close the
original product issue). Replaces closed dotnet#39122.

<!--
Are you targeting main? All PRs should target the main branch unless
otherwise noted.
-->
…otnet#39128)

<!-- Please let the below note in for people that find this PR -->
> [!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](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!

<!--
!!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING
MAIN. !!!!!!!
-->

### Description of Change

<!-- Enter description of the fix in this section -->

Add `App.WaitForElement("Options");` immediately before the first
`Options` tap in `VerifyEditorTextWhenAlignedVertically`, matching the
neighboring horizontal-alignment test. This synchronizes the initial
interaction with element availability using the existing timeout
defaults. All subsequent interactions, screenshot assertions, cropping
values, pre-existing whitespace, test order/category and helpers are
unchanged. No product changes.

This is a clean, main-based replacement for closed predecessor
[dotnet#39123](dotnet#39123), not a retarget or
transplant of its candidate branch history. Base at creation:
`32583cd272cf1ac485243fd13d322bb13f147914`.

**Candidate evidence, not main validation:** Before the candidate fix,
[UI build
1622359](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1622359)
showed the Android CoreCLR-labeled API30 null reference at the first
`Options` tap (log 5696, line 987), followed by a same-head later pass
(log 5696, line 2597). The predecessor's [UI build
1622632](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1622632)
subsequently passed this test in all five scheduled configurations /
eight observed executions, including original attempts (logs 4688:909,
5332:939+1931, 5090:572, 5366:725+3205, 5475:528+1916). These
observations are encouraging but do not prove permanent flake
elimination or validate this main-based replacement.

**Static validation:**
- `dotnet format whitespace --folder --include
src/Controls/tests/TestCases.Shared.Tests/Tests/FeatureMatrix/EditorFeatureTests.cs`
— passed. Its unrelated removal of existing `CropBottomValue` trailing
whitespace was restored before committing.
- `git diff --check` — passed.
- Exact byte comparison — passed: precisely the requested insertion;
every other byte, including all screenshot checks, unchanged. Command:

```sh
python3 -c 'import pathlib,subprocess; p="src/Controls/tests/TestCases.Shared.Tests/Tests/FeatureMatrix/EditorFeatureTests.cs"; b=subprocess.check_output(["git","show","HEAD:"+p]); n=b"\tpublic void VerifyEditorTextWhenAlignedVertically()\n\t{\n"; assert b.count(n)==1; assert pathlib.Path(p).read_bytes()==b.replace(n,n+b"\t\tApp.WaitForElement(\"Options\");\n",1); print("PASS: exact one-line insertion; every other byte unchanged")'
```

The comparison ran before committing, with `HEAD` pointing to the
unchanged main base. Analysis-only `pr-finalize` found the title/body
consistent with the tiny diff; no review or approval was posted. Native
compilation and UI execution were not run locally and remain pending CI.

### Issues Fixed

<!-- Please make sure that there is a bug logged for the issue being
fixed. The bug should describe the problem and how to reproduce it. -->

No separately filed product issue; addresses the Editor test's initial
Options readiness failure documented in predecessor
[dotnet#39123](dotnet#39123).

<!--
Are you targeting main? All PRs should target the main branch unless
otherwise noted.
-->

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
This pull request updates the following dependencies

[marker]: <> (Begin:a71c12d9-5aa4-4b46-e2d6-08da0cf8cd95)
## From https://github.com/dotnet/xharness
- **Subscription**:
[a71c12d9-5aa4-4b46-e2d6-08da0cf8cd95](https://maestro.dot.net/subscriptions?search=a71c12d9-5aa4-4b46-e2d6-08da0cf8cd95)
- **Build**:
[20260930.3](https://dev.azure.com/dnceng/internal/_build/results?buildId=3091941)
([334604](https://maestro.dot.net/channel/2/github:dotnet:xharness/build/334604))
- **Date Produced**: September 30, 2026 5:18:20 PM UTC
- **Commit**:
[3e092b0335764b0b215cb7aaea7c516ed2bf7ed8](dotnet/xharness@3e092b0)
- **Branch**: [main](https://github.com/dotnet/xharness/tree/main)

[DependencyUpdate]: <> (Begin)

- **Dependency Updates**:
  - From [11.0.0-prerelease.26466.1 to 11.0.0-prerelease.26480.3][1]
     - Microsoft.DotNet.XHarness.CLI
     - Microsoft.DotNet.XHarness.TestRunners.Common
     - Microsoft.DotNet.XHarness.TestRunners.Xunit

[1]: dotnet/xharness@22d4210...3e092b0

[DependencyUpdate]: <> (End)


[marker]: <> (End:a71c12d9-5aa4-4b46-e2d6-08da0cf8cd95)

Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
)

<!-- Please let the below note in for people that find this PR -->
[!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](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!

### Description of Change

`JsonLocalizationStringsAreTranslated` assumes the repository root is
five parent directories above the test working directory. In an isolated
macOS Helix payload this escapes into the worker's scratch tree.
Recursive enumeration then encounters unreadable Unix-file-mode test
directories and throws `UnauthorizedAccessException` before any
localization comparison. The same mechanism was confirmed in both Debug
and Release on `net11.0` and `release/11.0.1xx-rc2`.

This change:
- Copies the template localization JSON files into a dedicated
`TemplateLocalization` directory in both build and publish output,
preserving each template's directory structure.
- Discovers files only within that directory, relative to
`AppContext.BaseDirectory`, and anchors the audit reports there as well.
- Fails explicitly when the packaged dataset is missing or empty,
incomplete, or missing a required culture file, instead of passing
vacuously or returning early.
- Captures the source baseline count in test assembly metadata and
compares it with the packaged baseline count. This detects a whole
missing template without hard-coding the current template count.

Translation discrepancies remain audit-log output, as before. The three
already-skipped repository-dependent localization checks remain skipped.
There are no framework or public API changes.

Do not fix this by suppressing access errors or skipping the active
theory: the file search must remain inside its own payload and exercise
real template data.

### Issues Fixed

No linked GitHub issue. Addresses the recurring
`JsonLocalizationStringsAreTranslated` Helix failures on `net11.0` and
`release/11.0.1xx-rc2`. A separate `BusySentWhenVisiblePageSetToBusy`
assertion observed during the investigation is not addressed by this PR.

This PR targets `main`; the same fix can be backported to the affected
.NET 11 branches.

### Validation

The original payload-scoping fix was independently reviewed with Gemini
and Sonnet. Subsequent PR review feedback added the build-derived
baseline-count guard.

| Check | Result |
| --- | --- |
| Local Debug localization tests on Windows / net10.0 | 13 passed; 3
existing skipped checks unchanged |
| Published Release payload | 195 unique JSON assets across 13
templates, all byte-identical to source; the unfixed payload contained
none |
| Published tests executed outside the repository | All 13 culture cases
passed |
| Missing / empty packaged dataset | All 13 cases failed with the
expected assertions |
| One missing Czech culture file | Exactly 1 expected failure, 12 passes
|
| One whole template removed before the count guard | All 13 cases still
passed, reproducing the review finding |
| One whole template removed after the count guard | All 13 cases
failed: expected 13 baselines, actual 12 |
| Dataset restored after the count guard | All 13 cases passed; 3
existing skipped checks unchanged |

Native macOS execution has not been performed locally. Confidence comes
from the confirmed failure stacks and removal of the unbounded
repository-root traversal; CI validation is still required.

---------

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

Automates Azure DevOps validation for the repository's generated CI-fix
pull requests.

- Adds strict same-repository gating for the automated fingerprint:
`github-actions[bot]`, `ci-fix/**` head, `agentic-workflows` label, and
the correct title/base pairing for `main` and `net11.0`.
- Uses trusted `pull_request_target` execution plus trusted-main
`workflow_run` reconciliation for both fixer workflows, including cases
where GitHub-token-created PR events are suppressed or approval-gated.
Every configured PR event reconciles live eligible open PR heads rather
than relying on stale webhook identities.
- Refreshes nominated PRs individually and verifies each test-merge
commit contains the refreshed source head as its second parent before
queueing or deduplication. Missing, stale, or conflicting merge pairs
produce explicit per-PR failures without blocking other verified heads;
the overall run remains non-success when eligible work cannot be
dispatched. Live eligibility and the head/merge pair are revalidated for
each pipeline under the same partial-failure boundary as dedupe and
queue operations.
- Queues MAUI validation definitions 302 (`maui-pr`), 313
(`maui-pr-uitests`), and 314 (`maui-pr-devicetests`) with the verified
PR merge ref/SHA, provider `triggerInfo`, and serialized
`system.pullRequest.*` parameters matching observed normal Azure PR
build payloads. The system parameters include the bare target branch
used by pipeline conditions and the source head SHA. PR-head check
association remains subject to live canary verification.
- Adds per-pipeline/head-SHA deduplication, bounded retries, safe
ambiguous-POST reconciliation, explicit partial-failure reporting,
summaries, and build links. Nested PowerShell request timeouts enter
reconciliation without repeating the POST; failed reconciliation
preserves possible-acceptance uncertainty. Deduplication and both fixer
instructions require the PR merge ref and exact source-head metadata
when matching automatic builds.
- Both fixer variants retain primary-pipeline whole-build validation for
build-only fixes. When a build break originates in definition 313 or
314, merely observing its exact-head run is insufficient: all relevant
originating platform build legs must be completed and successful before
marking ready. Missing, unknown, pending, failed, or canceled relevant
evidence stops readiness; unrelated test-leg flakes do not. Readiness
audit comments identify the validated primary and originating
pipeline/build evidence.
- A shared seven-minute dispatch budget caps HTTP timeouts and backoff
under the ten-minute job limit. Budget exhaustion, including during
queue-time revalidation, preserves completed results and explicitly
reports unprocessed work without implying those pipelines submitted a
queue POST.
- Never checks out or executes PR-controlled code; authentication uses
the existing main-branch OIDC trust and no PAT.
- Updates the CI-fixer descriptions, setup documentation, and compiled
gh-aw lock files.

## Validation

Completed locally:

- 73 focused Pester tests passed at `d0cf55b`, independently rerun,
including offline full-script reconciliation, delayed-event regressions,
behavioral queue-response coverage, shared-budget exhaustion, and
accurate partial-result reporting across multiple PRs. Coverage includes
nested timeout exceptions with real duplicate identity matching,
outer/nested JSON contract assertions for main and net11.0,
stale/malformed merge-parent rejection, refreshed eligibility
revocation, actual entrypoint mixed/all-unverifiable failure routing,
preservation of completed results after queue-time revalidation
failures, and dedupe/fixer source-head contract alignment. The readiness
additions assert prompt requirements in both sources; they do not
simulate agent execution.
- A local stalled-HTTP-server repro confirms actual PowerShell
`Invoke-RestMethod` timeout exceptions are recognized as transient after
the fix. No Azure request was made by this repro.
- PowerShell parse validation passed.
- `actionlint` passed for the new dispatcher workflow. Direct linting of
the generated fixer locks reports the same six pre-existing findings
before and after this readiness change; the gh-aw actionlint wrapper
returned tooling exit 125, not a clean lint result.
- Both gh-aw v0.86.2 strict compile/no-emit checks passed for the
readiness follow-up, and both locks were regenerated with zero compiler
warnings. This follow-up changes only their body hashes, not workflow
configuration.
- Dry-run payload validation passed for all three pipeline definitions.
- `git diff --check` passed.

## Rollout notes

Merging enables the automation. Only pipeline 302 OIDC queueing has live
proof so far. Azure DevOps Basic access and Queue builds permission for
all three definitions, plus exact PR-head check association, remain
rollout/canary requirements and should be verified after merge. No live
build was queued by this PR-creation or review-follow-up work.

---------

Co-authored-by: PureWeen <223556219+Copilot@users.noreply.github.com>
When SelectedItem is set (or bound) before ItemsSource, for example because of
the XAML attribute order, the Picker ends up with no selection and pushes null
back through the TwoWay binding. Cover direct sets, bindings and XAML pages for
all inflators. The tests fail until the selection is reconciled when the items
are loaded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
When SelectedItem was set before ItemsSource, UpdateSelectedIndex couldn't find
it in the empty Items, and ResetItems then clamped the -1 index, which set
SelectedItem to null (and pushed null back through a TwoWay binding).

When there's no valid SelectedIndex but SelectedItem is set, look the item up
in the new ItemsSource, as ResyncItemsAndReconcileSelection already does after
a collection reset. A valid SelectedIndex is still used as before.

Fixes dotnet#30644

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions

github-actions Bot commented Oct 6, 2026

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 -- 39175

Or

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

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
There may be pipelines that require an authorized user to comment /azp run to run.

@dotnet-policy-service dotnet-policy-service Bot added the community ✨ Community Contribution label Oct 6, 2026
@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Hey there @@MykhailoDav! Thank you so much for your PR! Someone from the team will get assigned to your PR shortly and we'll get it reviewed.

@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Hey there @MykhailoDav! Thank you so much for your PR! Someone from the team will get assigned to your PR shortly and we'll get it reviewed.

@kubaflo

This comment has been minimized.

@kubaflo

kubaflo commented Oct 6, 2026

Copy link
Copy Markdown
Contributor

/azp run

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

github-actions Bot commented Oct 6, 2026

Copy link
Copy Markdown
Contributor

Note

🔍 /review started

AzDO build 15582077 is running for android.

The s/agent-review-in-progress label stays on this PR while the run is active. The final recommendation and outcome labels are posted only after Gate, expert review, and Deep UI tests finish.

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 3 pipeline(s).

@MauiBot

MauiBot commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator

AI Review Summary

@MykhailoDav — new AI review results are available based on commit c525a6d.

Gate Passed Confidence Unknown Platform Android


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

Gate Result: ✅ PASSED

Platform: ANDROID · Base: main · Merge base: f7530d0a

Test Without Fix (expect FAIL) With Fix (expect PASS)
🧪 PickerTestsNestedClass PickerTestsNestedClass 🔍 NO MATCH 🔍 NO MATCH
📄 Maui30644 Maui30644 ✅ FAIL — 113s ✅ PASS — 36s
📄 Test Test ✅ FAIL — 142s ✅ PASS — 125s
🔴 Without fix — 🧪 PickerTestsNestedClass: 🔍 NO MATCH · 102s

(no coded error found; showing last 1200 chars)

rols.Core.csproj (in 38 ms).
  Restored /home/vsts/work/1/s/src/Controls/src/BindingSourceGen/Controls.BindingSourceGen.csproj (in 64 ms).
  Restored /home/vsts/work/1/s/src/Controls/Maps/src/Controls.Maps.csproj (in 23 ms).
  Restored /home/vsts/work/1/s/src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj (in 2.02 sec).
Test run for /home/vsts/work/1/s/artifacts/bin/Controls.Core.UnitTests/Debug/net10.0/Microsoft.Maui.Controls.Core.UnitTests.dll (.NETCoreApp,Version=v10.0)
VSTest version 18.0.2 (x64)
Starting test execution, please wait...
A total of 1 test files matched the specified pattern.
[xUnit.net 00:00:00.00] xUnit.net VSTest Adapter v2.8.2+699d445a1a (64-bit .NET 10.0.13)
[xUnit.net 00:00:00.16]   Discovering: Microsoft.Maui.Controls.Core.UnitTests
[xUnit.net 00:00:01.47]   Discovered:  Microsoft.Maui.Controls.Core.UnitTests
[xUnit.net 00:00:01.49]   Starting:    Microsoft.Maui.Controls.Core.UnitTests
[xUnit.net 00:00:01.50]   Finished:    Microsoft.Maui.Controls.Core.UnitTests
No test matches the given testcase filter `PickerTestsNestedClass` in /home/vsts/work/1/s/artifacts/bin/Controls.Core.UnitTests/Debug/net10.0/Microsoft.Maui.Controls.Core.UnitTests.dll
🟢 With fix — 🧪 PickerTestsNestedClass: 🔍 NO MATCH · 66s
  Determining projects to restore...
  All projects are up-to-date for restore.
Test run for /home/vsts/work/1/s/artifacts/bin/Controls.Core.UnitTests/Debug/net10.0/Microsoft.Maui.Controls.Core.UnitTests.dll (.NETCoreApp,Version=v10.0)
VSTest version 18.0.2 (x64)
Starting test execution, please wait...
A total of 1 test files matched the specified pattern.
[xUnit.net 00:00:00.00] xUnit.net VSTest Adapter v2.8.2+699d445a1a (64-bit .NET 10.0.13)
[xUnit.net 00:00:00.26]   Discovering: Microsoft.Maui.Controls.Core.UnitTests
[xUnit.net 00:00:03.21]   Discovered:  Microsoft.Maui.Controls.Core.UnitTests
[xUnit.net 00:00:03.23]   Starting:    Microsoft.Maui.Controls.Core.UnitTests
[xUnit.net 00:00:03.25]   Finished:    Microsoft.Maui.Controls.Core.UnitTests
No test matches the given testcase filter `PickerTestsNestedClass` in /home/vsts/work/1/s/artifacts/bin/Controls.Core.UnitTests/Debug/net10.0/Microsoft.Maui.Controls.Core.UnitTests.dll
🔴 Without fix — 📄 Maui30644: FAIL ✅ · 113s

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

     at Microsoft.Maui.Controls.Xaml.UnitTests.Maui30644.Test.PickerSelectedItemBeforeItemsSourceIsSelected(XamlInflator inflator) in /_/src/Controls/tests/Xaml.UnitTests/Issues/Maui30644.xaml.cs:line 45
   at System.RuntimeMethodHandle.InvokeMethod(ObjectHandleOnStack target, Void** arguments, ObjectHandleOnStack sig, BOOL isConstructor, ObjectHandleOnStack result)
   at System.Reflection.MethodBaseInvoker.InterpretedInvoke_Method(Object obj, IntPtr* args)
   at System.Reflection.MethodBaseInvoker.InvokeDirectByRefWithFewArgs(Object obj, Span`1 copyOfArgs, BindingFlags invokeAttr)
   at InvokeStub_Test.PickerSelectedItemBeforeItemsSourceIsSelected(Object, Span`1)
   at System.Reflection.MethodBaseInvoker.InvokeWithOneArg(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
🟢 With fix — 📄 Maui30644: PASS ✅ · 36s
  Determining projects to restore...
  All projects are up-to-date for restore.
Test run for /home/vsts/work/1/s/artifacts/bin/Controls.Xaml.UnitTests/Debug/net10.0/Microsoft.Maui.Controls.Xaml.UnitTests.dll (.NETCoreApp,Version=v10.0)
VSTest version 18.0.2 (x64)
Starting test execution, please wait...
A total of 1 test files matched the specified pattern.
[xUnit.net 00:00:00.00] xUnit.net VSTest Adapter v2.8.2+699d445a1a (64-bit .NET 10.0.13)
[xUnit.net 00:00:00.41]   Discovering: Microsoft.Maui.Controls.Xaml.UnitTests
[xUnit.net 00:00:04.82]   Discovered:  Microsoft.Maui.Controls.Xaml.UnitTests
[xUnit.net 00:00:04.83]   Starting:    Microsoft.Maui.Controls.Xaml.UnitTests
[xUnit.net 00:00:05.08]   Finished:    Microsoft.Maui.Controls.Xaml.UnitTests
  Passed PickerSelectedItemBeforeItemsSourceIsSelected(inflator: Runtime) [154 ms]
  Passed PickerSelectedItemBeforeItemsSourceIsSelected(inflator: XamlC) [7 ms]
  Passed PickerSelectedItemBeforeItemsSourceIsSelected(inflator: SourceGen) [2 ms]
Test Run Successful.
Total tests: 3
     Passed: 3
 Total time: 5.9497 Seconds
🔴 Without fix — 📄 Test: FAIL ✅ · 142s

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

     at Microsoft.Maui.Controls.Xaml.UnitTests.Maui30644.Test.PickerSelectedItemBeforeItemsSourceIsSelected(XamlInflator inflator) in /_/src/Controls/tests/Xaml.UnitTests/Issues/Maui30644.xaml.cs:line 45
   at System.RuntimeMethodHandle.InvokeMethod(ObjectHandleOnStack target, Void** arguments, ObjectHandleOnStack sig, BOOL isConstructor, ObjectHandleOnStack result)
   at System.Reflection.MethodBaseInvoker.InvokeDirectByRefWithFewArgs(Object obj, Span`1 copyOfArgs, BindingFlags invokeAttr)
   at InvokeStub_Test.PickerSelectedItemBeforeItemsSourceIsSelected(Object, Span`1)
   at System.Reflection.MethodBaseInvoker.InvokeWithOneArg(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
🟢 With fix — 📄 Test: PASS ✅ · 125s

(no coded error found; showing last 1200 chars)

wsMeaningfullException(inflator: SourceGen) [6 ms]
  Passed xStaticThrowsMeaningfullException(inflator: XamlC) [112 ms]
  Passed xStaticThrowsMeaningfullException(inflator: Runtime) [3 ms]
  Passed DynamicResourceOnBO(inflator: XamlC) [1 ms]
  Passed DynamicResourceOnBO(inflator: SourceGen) [1 ms]
  Passed DynamicResourceOnBO(inflator: Runtime) [3 ms]
  Passed VerifyCorrectTypesUsed(inflator: SourceGen) [1 ms]
  Passed VerifyCorrectTypesUsed(inflator: Runtime) [2 ms]
  Passed VerifyCorrectTypesUsed(inflator: XamlC) [139 ms]
  Passed VerifyCorrectTypesUsed(inflator: SourceGen) [1 ms]
  Passed VerifyCorrectTypesUsed(inflator: XamlC) [94 ms]
  Passed VerifyCorrectTypesUsed(inflator: Runtime) [2 ms]
[xUnit.net 00:01:49.89]   Finished:    Microsoft.Maui.Controls.Xaml.UnitTests
  Passed VerifyCorrectTypesUsed(inflator: SourceGen) [1 ms]
  Passed VerifyCorrectTypesUsed(inflator: XamlC) [201 ms]
  Passed VerifyCorrectTypesUsed(inflator: Runtime) [3 ms]
  Passed ShouldPass(inflator: SourceGen) [< 1 ms]
  Passed ShouldPass(inflator: XamlC) [< 1 ms]
  Passed ShouldPass(inflator: Runtime) [1 ms]
Test Run Successful.
Total tests: 2021
     Passed: 2013
    Skipped: 8
 Total time: 1.8474 Minutes

⚠️ Failure Details

  • 🔍 PickerTestsNestedClass without fix: test filter matched 0 tests
    • filter: PickerTestsNestedClass
  • 🔍 PickerTestsNestedClass with fix: test filter matched 0 tests
    • filter: PickerTestsNestedClass
📁 Fix files reverted (1 files)
  • src/Controls/src/Core/Picker/Picker.cs

📋 Pre-Flight — Context & Validation

⚠️ Pre-Flight did not produce output on this run.

The Copilot expert-review task ended before this phase was persisted, usually because the review-stage time budget expired or the CI agent encountered a transient authentication/runtime problem. Earlier completed sections remain valid, but this review is incomplete without this phase.

Next step: re-comment /review to retry on a fresh agent. If this repeats across runs, a maintainer should inspect the reviewer token and Task 3 logs.


🔬 Code Review — Deep Analysis

⚠️ Code Review did not produce output on this run.

The Copilot expert-review task ended before this phase was persisted, usually because the review-stage time budget expired or the CI agent encountered a transient authentication/runtime problem. Earlier completed sections remain valid, but this review is incomplete without this phase.

Next step: re-comment /review to retry on a fresh agent. If this repeats across runs, a maintainer should inspect the reviewer token and Task 3 logs.


🛠️ Try-Fix — Analysis & Comparison

⚠️ Try-Fix did not produce output on this run.

The Copilot expert-review task ended before this phase was persisted, usually because the review-stage time budget expired or the CI agent encountered a transient authentication/runtime problem. Earlier completed sections remain valid, but this review is incomplete without this phase.

Next step: re-comment /review to retry on a fresh agent. If this repeats across runs, a maintainer should inspect the reviewer token and Task 3 logs.


🏁 Report — Final Recommendation

⚠️ Report / Final Recommendation did not produce output on this run.

The Copilot expert-review task ended before this phase was persisted, usually because the review-stage time budget expired or the CI agent encountered a transient authentication/runtime problem. Earlier completed sections remain valid, but this review is incomplete without this phase.

Next step: re-comment /review to retry on a fresh agent. If this repeats across runs, a maintainer should inspect the reviewer token and Task 3 logs.


🔗 Regression Cross-Reference

🔍 Regression Cross-Reference

⚠ Overlaps with prior bug-fix PRs — same files modified, but no exact line revert detected.

File Fix PR Fixed issue(s)
src/Controls/src/Core/Picker/Picker.cs #36470 #36465

📱 UI Tests — Picker

Detected UI test categories: Picker

✅ Deep UI tests — 54 passed, 0 failed across 1 category on platform-pool agent (replaces in-process counts above).

🧪 UI Test Execution Results (deep, platform pool)

Category Tests Snapshot diffs
Picker 54/54 ✓ —
📎 Download drop-deep-uitests artifact (TRX + snapshot diffs)

🧭 Next Steps — review latest findings

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

@MauiBot MauiBot added s/agent-review-incomplete AI review did not complete all expected phases s/agent-gate-passed AI verified tests catch the bug (fail without fix, pass with fix) s/agent-reviewed PR was reviewed by AI agent workflow (full 4-phase review) and removed s/agent-review-in-progress AI review is currently running for this PR labels Oct 6, 2026
@github-actions github-actions Bot added the s/agent-review-in-progress AI review is currently running for this PR label Oct 6, 2026
@github-actions

github-actions Bot commented Oct 6, 2026

Copy link
Copy Markdown
Contributor

Note

🔍 /review started

AzDO build 15583760 is running for android.

The s/agent-review-in-progress label stays on this PR while the run is active. The final recommendation and outcome labels are posted only after Gate, expert review, and Deep UI tests finish.

@kubaflo

This comment has been minimized.

@kubaflo
kubaflo changed the base branch from main to inflight/current October 6, 2026 17:10
@kubaflo
kubaflo merged commit 78f5b1d into dotnet:inflight/current Oct 6, 2026
194 of 208 checks passed
@MykhailoDav
MykhailoDav deleted the fix-30644-picker-selecteditem-before-itemssource branch October 6, 2026 17:10
@MauiBot MauiBot removed the s/agent-review-in-progress AI review is currently running for this PR label Oct 6, 2026
@github-actions github-actions Bot added this to the .NET 10 SR12 milestone Oct 6, 2026
kubaflo pushed a commit that referenced this pull request Oct 6, 2026
)

### Description of Change

A `Picker` loses its selection when `SelectedItem` is set before
`ItemsSource`, which is what happens when `SelectedItem` comes first in
XAML:

```xml
<Picker SelectedItem="{Binding Selected}" ItemsSource="{Binding Values}" />  <!-- nothing selected -->
<Picker ItemsSource="{Binding Values}" SelectedItem="{Binding Selected}" />  <!-- works -->
```

Because `SelectedItem` is `TwoWay`, the lost selection is also written
back: `Selected` in the view model becomes `null`.

**Root cause**

1. Setting `SelectedItem` calls `UpdateSelectedIndex`, which looks the
item up in the still-empty `Items` and leaves `SelectedIndex` at -1.
2. Setting `ItemsSource` calls `ResetItems`, which calls
`ClampSelectedIndex(SelectedIndex)`, i.e. `ClampSelectedIndex(-1)`.
3. `ClampSelectedIndex(-1)` calls `UpdateSelectedItem(-1)`, which sets
`SelectedItem` to `null`.

**Fix**

In `ResetItems`, when there's no valid `SelectedIndex` but
`SelectedItem` is set, look the item up in the new `ItemsSource`. This
is how `ResyncItemsAndReconcileSelection` already reconciles the
selection after a collection reset, and it is the `SelectedItem`
counterpart of #35629, which made a `SelectedIndex` set before the items
order-independent.

Unchanged:
- A valid `SelectedIndex` is still used as before. `ResetItems` also
runs when the handler connects and when `ItemDisplayBinding` changes.
- A `SelectedItem` that isn't in `ItemsSource` is still cleared.
- `SelectedIndexChanged` is raised once, the same as when `ItemsSource`
is set first and `SelectedItem` second.

`Picker.cs` is identical on `net11.0`, so the issue is there too.

**Tests**

- `PickerTests` (Core.UnitTests):
  - `SelectedItemSetBeforeItemsSourceIsSelected`
- `SelectedItemBoundBeforeItemsSourceKeepsBoundValue` (bindings applied
in that order; the bound value is kept)
- `SelectedItemNotInItemsSourceSetBeforeItemsSourceIsCleared` (behavior
unchanged)
- `Maui30644` (Xaml.UnitTests, Runtime/XamlC/SourceGen): the reporter's
page, with one picker in each attribute order and compiled bindings.

| | Without fix | With fix |
|---|---|---|
| `PickerTests` | 60 passed, 2 failed | 62 passed |
| `Maui30644` | 3 failed (`SelectedIndex` is -1 for every inflator) | 3
passed |

With the fix, the full suites pass: Controls.Core.UnitTests 5721 passed
/ 30 skipped, and Controls.Xaml.UnitTests 2013 passed / 8 skipped.

### Issues Fixed

Fixes #30644
kubaflo pushed a commit that referenced this pull request Oct 13, 2026
)

### Description of Change

A `Picker` loses its selection when `SelectedItem` is set before
`ItemsSource`, which is what happens when `SelectedItem` comes first in
XAML:

```xml
<Picker SelectedItem="{Binding Selected}" ItemsSource="{Binding Values}" />  <!-- nothing selected -->
<Picker ItemsSource="{Binding Values}" SelectedItem="{Binding Selected}" />  <!-- works -->
```

Because `SelectedItem` is `TwoWay`, the lost selection is also written
back: `Selected` in the view model becomes `null`.

**Root cause**

1. Setting `SelectedItem` calls `UpdateSelectedIndex`, which looks the
item up in the still-empty `Items` and leaves `SelectedIndex` at -1.
2. Setting `ItemsSource` calls `ResetItems`, which calls
`ClampSelectedIndex(SelectedIndex)`, i.e. `ClampSelectedIndex(-1)`.
3. `ClampSelectedIndex(-1)` calls `UpdateSelectedItem(-1)`, which sets
`SelectedItem` to `null`.

**Fix**

In `ResetItems`, when there's no valid `SelectedIndex` but
`SelectedItem` is set, look the item up in the new `ItemsSource`. This
is how `ResyncItemsAndReconcileSelection` already reconciles the
selection after a collection reset, and it is the `SelectedItem`
counterpart of #35629, which made a `SelectedIndex` set before the items
order-independent.

Unchanged:
- A valid `SelectedIndex` is still used as before. `ResetItems` also
runs when the handler connects and when `ItemDisplayBinding` changes.
- A `SelectedItem` that isn't in `ItemsSource` is still cleared.
- `SelectedIndexChanged` is raised once, the same as when `ItemsSource`
is set first and `SelectedItem` second.

`Picker.cs` is identical on `net11.0`, so the issue is there too.

**Tests**

- `PickerTests` (Core.UnitTests):
  - `SelectedItemSetBeforeItemsSourceIsSelected`
- `SelectedItemBoundBeforeItemsSourceKeepsBoundValue` (bindings applied
in that order; the bound value is kept)
- `SelectedItemNotInItemsSourceSetBeforeItemsSourceIsCleared` (behavior
unchanged)
- `Maui30644` (Xaml.UnitTests, Runtime/XamlC/SourceGen): the reporter's
page, with one picker in each attribute order and compiled bindings.

| | Without fix | With fix |
|---|---|---|
| `PickerTests` | 60 passed, 2 failed | 62 passed |
| `Maui30644` | 3 failed (`SelectedIndex` is -1 for every inflator) | 3
passed |

With the fix, the full suites pass: Controls.Core.UnitTests 5721 passed
/ 30 skipped, and Controls.Xaml.UnitTests 2013 passed / 8 skipped.

### Issues Fixed

Fixes #30644
kubaflo added a commit that referenced this pull request Oct 13, 2026
<!-- Please let the below note in for people that find this PR -->
> [!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](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!

<!--
!!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING
MAIN. !!!!!!!
-->

### Description of Change

<!-- Enter description of the fix in this section -->

Add `/review gate` as an explicit existing-test-only mode without
replacing or shortening the existing hosted `/review` process. Bare
`/review`, its platform/branch options, and dispatches that omit the new
flag continue to select the full review. `/review tests` and `/review
performance` remain independent.

The gate retains the existing selected unit, XAML, device, and UI
verifier, including failure-only verification for test-only changes,
bounded native selection, retry handling, and skipped/inconclusive
outcomes. It does not generate missing tests or run expert code review,
Try-Fix, deep-category UI sweeps, or Copilot inference. These exclusions
apply only to gate mode; hosted `/review` and local full-review tools
retain their existing phases.

Publish a commit-pinned, bounded report with a closed **Gate analysis**
section. The original expandable layout from #38807 is refined to match
[the user-selected test-failure-analysis
comment](#37572 (comment)):
an author/commit quote, flat-square result/platform/commit badges, and
readable result tables grouped by test type. At the user's request, omit
the Scope badge/text, Follow-up accordion, and report/artifact-link
footer. Only recognized diagnostic fields are rendered; raw
execution-log excerpts remain escaped in their own collapsed section
rather than displaying a raw Markdown document. Posting runs on a fresh
agent and only maintains gate signals and publisher-owned gate comments;
it does not approve PRs or edit their titles/descriptions. The trigger
and scheduled recovery recognize both commands and preserve the selected
mode after permission and source-comment revalidation. Previously
removed existing full-review coverage is restored unchanged; no new
pipeline/configuration tests are added.

Live validation exposed two selection defects: a closed nested Picker
helper was mistaken for its test fixture, and a nested XAML `Test`
fixture became an assembly-wide filter. Resolve containing class scopes
using the existing C# declaration scanner, and group nested XAML
fixtures by their page. Build errors and no-match results remain visibly
unverified in both detailed evidence and the console summary. Keep the
verifier's existing passing policy, but make the publication explicit
that unmatched/inconclusive groups are not successful execution
evidence.

A publication canary exposed an unnecessary repository-label metadata
PATCH returning HTTP 404. The gate now assigns the existing gate labels
without editing repository-wide descriptions/colors. Required assignment
failures explicitly fail publication instead of being ignored. The final
live publication completed without that warning.

**Additive routing at production source
`3e96214dacd9c65b3e99b0f23801e197722d0fc3`:**

| Request | Selected pipeline |
| --- | --- |
| `/review` or normal/default dispatch | Existing full review, Deep UI,
final AI Summary, cleanup, and telemetry |
| `/review gate` or `gate_only=true` | Setup/Gate, fresh gate-only
publication, and cleanup |
| `/review tests` / `/review performance` | Their unchanged independent
workflows |

`eng/pipelines/ci-copilot.yml` keeps the original full stages inline and
defaults `GateOnly` to **false**. Its explicit true branch selects
`pr-review-gate.yml` at compile time, so gate runs contain no
full-review/inference, Deep UI, or token-aggregation jobs. The parent
passes the shared 150-minute Gate task limit as a typed template
parameter; an actual Azure compiler preview exposed that the extracted
stage template cannot read the parent's static timeout directly. No new
Azure definition, secret, permission, or OIDC trust is required.

**Current validation:**

- `actionlint .github/workflows/review-trigger.yml
.github/workflows/review-trigger-recovery.yml` - passed. Both Azure YAML
files parse, all four changed production PowerShell scripts and 48
compile-time-expanded embedded PowerShell blocks parse, and `git diff
--check` passes.
- Azure Runs API `previewRun=true` on definition 27723 with the
production branch and exact SHA above - **nine successful compiler
previews**: omitted mode, explicit false on
Android/iOS/Catalyst/Windows, and explicit true on all four platforms.
Omitted mode expands identically to false. Full mode retains all five
original stages; gate mode includes only `Gate`, `PostGate`, and
`CleanupReviewLock`, with a 150-minute credential-free Gate task.
- `Invoke-Pester -Path @('.github/scripts/ReviewTrigger.Tests.ps1',
'.github/scripts/Recover-MissedReviewCommands.Tests.ps1',
'.github/scripts/Review-PR.Tests.ps1',
'.github/scripts/CopilotPipeline.Tests.ps1',
'.github/scripts/shared/Prepare-UITestFailureAnalysis.Tests.ps1',
'.github/scripts/Post-AISummaryComment.Tests.ps1') -Output Minimal
-PassThru` - **246 passed, two unchanged model-pin assertions failed**
against the independent, untouched `Review-Tests.ps1`. The restored
existing suites and implicated product files match the original/current
main versions; these unrelated assertions are not changed to manufacture
a green result.
- [Remote additive canary
15652574](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_build/results?buildId=15652574),
queued by [the existing trusted-main
dispatcher](https://github.com/dotnet/maui/actions/runs/38237622825),
**succeeded** on this draft PR. Only Gate, fresh PostGate, and Cleanup
jobs ran; all three succeeded. The no-MAUI-tests control truthfully
reported **SKIPPED**, not native test execution. Its 7,062-byte GateLogs
artifact contains regular allowlisted diagnostics. The new [MauiBot
report](#39189 (comment))
has three badges and a closed Gate analysis with no Scope, Follow-up, or
footer; its reviewed head and protected baseline are pinned. Actual
GitHub state confirms no gate pass/fail or full-review signals and a
released lock. Distinct hosted worker IDs confirm fresh-agent
publication. Direct queue access was denied; the already-authorized
dispatcher was used without changing credentials or trust.
- This pre-merge canary uses isolated source
`783a98445b269b3e9e30fef82e98d898ada3a74f` on
`kubaflo-gate-only-additive-canary-3e96214`. It differs from production
only in the declared `GateOnly` default, temporarily true because the
old main dispatcher cannot pass the new input. Its actual Azure-expanded
stages are identical to production with explicit true. The production PR
remains at the SHA above with default **false**.
- `Get-CIStatus.ps1 -PRNumber 39189 -Repository dotnet/maui -MaxJobs 100
-MaxFailureLines 20 -NoCache` - completed and refreshed after the
canary; [normal maui-pr build
1631878](https://dev.azure.com/dnceng-public/cbb18261-c48f-4abb-8651-8cdcb5474649/_build/results?buildId=1631878)
is still in progress for raw source
`3e96214dacd9c65b3e99b0f23801e197722d0fc3` and merge source
`74b9a40864ccb43a4079c8bb5d50fd20d53ea0ef`. The latest snapshot has six
succeeded jobs, 20 pending/running, and no failures. Pending CI is not
passing CI.

<details>
<summary>Earlier source-specific Gate execution, ten-PR canaries, and
compact-comment validation</summary>

The evidence below is preserved at its original execution/presentation
sources. It does not claim that the ten earlier canaries ran at the
newest additive source.

**End-to-end execution validation at source
`8e639d714ae303b62b537596cf488a476393bdc1`:**

- Final publisher PowerShell parsing and `git diff --cached --check`
passed. Earlier changed PowerShell/embedded Azure Bash and PowerShell
syntax checks, YAML parsing, and `actionlint
.github/workflows/review-trigger.yml
.github/workflows/review-trigger-recovery.yml` passed; the follow-ups do
not alter those YAML files.
- `Invoke-Pester -Path
@('.github/scripts/shared/Update-AgentLabels.Tests.ps1',
'.github/scripts/shared/Detect-TestsInDiff.Tests.ps1',
'.github/skills/verify-tests-fail-without-fix/scripts/Verify-TestsFail.Tests.ps1')
-Output Minimal -PassThru` — 176 passed, zero failed. The actual console
summary renderer was exercised with build-error, unmatched-filter, and
environment-error records; none appeared as expected assertion failures.
The final live log also correctly displays `BUILD ERR` rather than a
successful runtime failure.
- Azure Runs API previews succeeded for Android, iOS, Catalyst, and
Windows, with only Gate, PostGate, and lock cleanup jobs. The Android
`RunGate` task expands to 150 minutes. Those YAML configurations are
unchanged by the publisher follow-ups.
- The full detector against the exact #39175 test files selects only
`UnitTest:PickerTests` and `XamlUnitTest:Maui30644`, merging the XAML
page and code-behind rather than selecting a closed helper or broad
`Test` filter.
- The [hosted PowerShell suite at that
source](https://github.com/dotnet/maui/actions/runs/37511816441) matches
the existing workflow-equivalent selection: 2,456 passed and three
unchanged model-policy assertions failed against the independent
`/review tests` implementation/workflow files. Those unrelated model
pins are not changed here. The retained local full-review publisher's 75
existing regressions pass.
- [Skill validation at that
source](https://github.com/dotnet/maui/actions/runs/37511811901): static
validation passed, but the evaluation artifact exits 1 with 12 protocol
and 18 capability session-construction errors (`Session filesystem path
escapes root`), zero evaluation turns, and zero tokens. The unchanged
hermeticity harness separately fails while materializing missing
sparse-checkout blobs (`Could not reset index file to revision 'HEAD'`).
A green execution job is not a passing skill evaluation.
- [First live Picker/XAML canary on
#39175](https://dev.azure.com/DevDiv/DevDiv/_build/results?buildId=15583760):
`Maui30644` reproduced the issue and passed all three cases with the
fix, but the incorrect Picker filter matched no tests. The corrections
above address that selection. #39175 merged before publication; the
publisher correctly refused the closed target and cleanup released its
lock.
- [Second Android canary on
#37572](https://dev.azure.com/DevDiv/DevDiv/_build/results?buildId=15584958)
completed the Gate, fresh publication, and cleanup, but exposed the
repository-label metadata warning corrected above. Its owned report was
superseded by the final canary.
- [Final Android canary on
#37572](https://dev.azure.com/DevDiv/DevDiv/_build/results?buildId=15585863),
dispatched through [trusted
`main`](https://github.com/dotnet/maui/actions/runs/37511805027),
**succeeded at the exact source SHA above**. The selected
`AnimationTests` baseline cannot compile without the fix's internal
`HasTweener` API; all seven cases pass with the fix. This exercises the
verifier's existing compile-coupled mode, not runtime FAIL-to-PASS
reproduction.
- The final fresh agent published [the gate
report](#37572 (comment)),
applied the appropriate gate signal without repository-label metadata
edits, and minimized the previous owned report as outdated. Actual
GitHub state confirmed the old report minimized, the new report visible,
the tested head unchanged, and the in-progress lock absent. Cleanup
succeeded. No new full-review tracking/outcome labels or PR metadata
edits are claimed.

**Comment-presentation follow-up at source
`4d85e1f9307a83aba11c4603603876de8dcb121c`:**

- Publisher PowerShell parsing and `git diff --cached --check` passed.
The existing targeted label, detector, verifier, and local full-review
publisher suites passed: **251 tests, zero failures**. No new
pipeline/configuration tests were added.
- `Post-PRGate.ps1 -DryRun` used the exact final-canary diagnostic
transcript and immutable commit/run identities. The actual GitHub
Markdown API rendered four badges, a real before/after results table,
closed Gate analysis and Follow-up sections, and separately escaped
execution logs. The existing failure-only report writer was also
exercised with all four test types; skipped/no-report and merge-blocked
previews do not claim execution or a with-fix result.
- At the user's request, a separately guarded maintainer edit
reformatted **the same existing MauiBot comment**, rather than running
the publisher under a different identity or posting a duplicate. The
live comment's `body_html` read-back confirms the new rendering. MauiBot
attribution, the original verdict/run, both tested commits, the PR head,
and every label are unchanged. This is a presentation-only edit of
existing evidence, **not a new Azure verification run**.

**Requested ten-PR canary batch — all ten outcomes verified:**

All ten original runs were dispatched from trusted `main` with the
custom `pipeline_ref` at source
`4d85e1f9307a83aba11c4603603876de8dcb121c`. Original identities remain
preserved separately from corrective attempts. Corrective
unit-selection/publication runs used
`78bb5d3a3bc6da91357b5b116542d77bcc283449`; final Windows helper
validation used `d4397eaa8b855209c963ea8aad201508c3d45c05`; the
additional Windows bootstrap control used source
`ecd602ef48662a2a59f083d9db8fc5bdfb83fd45`. The batch is not represented
as ten runs at the newest source.

| PR | Platform | Verified outcome | Actual evidence |
| --- | --- | --- | --- |
|
[#37319](#37319 (comment))
| Android | FAILED |
[15596739](https://dev.azure.com/DevDiv/DevDiv/_build/results?buildId=15596739):
with-fix unit execution has 53 passes and two genuine stroke-transition
assertion failures. The independent UI case fails without the fix and
passes with it, but does not conceal the unit failures. Unit baseline is
compile-coupled to the new API. |
|
[#38441](#38441 (comment))
| Catalyst | PASSED |
[15596747](https://dev.azure.com/DevDiv/DevDiv/_build/results?buildId=15596747):
selected CollectionView height-update device case fails without the fix
and passes with it. |
|
[#38625](#38625 (comment))
| Android | PASSED |
[15596742](https://dev.azure.com/DevDiv/DevDiv/_build/results?buildId=15596742):
64 selected with-fix unit/SourceGen/XAML cases pass across five groups;
baseline compilation is coupled to the new API. |
|
[#39013](#39013 (comment))
| Android | PASSED |
[15596744](https://dev.azure.com/DevDiv/DevDiv/_build/results?buildId=15596744):
the selected CurrentItem-after-removal UI case runs and fails without
the fix, then runs and passes with it. |
|
[#38883](#38883 (comment))
| Catalyst, corrective host | FAILED |
[15597032](https://dev.azure.com/DevDiv/DevDiv/_build/results?buildId=15597032):
corrected `SkiaSharpSvgToolsTests` selects 16 cases, including both
PR-added SVG tests. All pass without the fix, on confirmation, and with
it. The selected unit tests do not reproduce this packaging change; this
is not a with-fix test failure. |
|
[#39213](#39213 (comment))
| Android; Windows control | SKIPPED | Original corrective Android
control
[15597033](https://dev.azure.com/DevDiv/DevDiv/_build/results?buildId=15597033)
and Windows bootstrap control
[15597596](https://dev.azure.com/DevDiv/DevDiv/_build/results?buildId=15597596)
both select no tests. No successful test execution or passing signal
claimed. |
|
[#37690](#37690 (comment))
| iOS, corrective run | INCONCLUSIVE |
[15597037](https://dev.azure.com/DevDiv/DevDiv/_build/results?buildId=15597037):
all 23 selected unit cases pass with the fix; baseline cannot compile
against the new cache API. Scoped device execution produces no fresh
XHarness XML, so overall verification stays inconclusive. |
|
[#38843](#38843 (comment))
| iOS, corrective run | INCONCLUSIVE |
[15597038](https://dev.azure.com/DevDiv/DevDiv/_build/results?buildId=15597038):
test-only ScrollView verification produces no fresh device result. No
with-fix execution is claimed. |
|
[#39185](#39185 (comment))
| Android | FAILED |
[15596745](https://dev.azure.com/DevDiv/DevDiv/_build/results?buildId=15596745):
selected `BindingPath_Parsed` passes without the fix, both
confirmations, and with the fix. Fresh method-scoped XML contains one
passing result; a different failure in the broader class cannot count as
reproduction of this selected test. Actual inflight baseline is
`262d95940f646b601093b36db4e27c691670d753`. |
|
[#39179](#39179 (comment))
| Windows, final helper run | PASSED, failure-only |
[15597455](https://dev.azure.com/DevDiv/DevDiv/_build/results?buildId=15597455):
ten actual HybridWebView UI cases, nine passing and one expected
baseline failure (`VerifyHybridWebViewWithShadow`, 6.11% screenshot
difference). Shared parser classifies the real results without the
former missing-helper exception. No with-fix run is claimed. |

For all ten outcomes, bounded artifact export, fresh MauiBot
publication, actual stored HTML, reviewed head, appropriate gate
signals, and lock cleanup are verified. At these execution sources,
reports rendered four badges and closed Gate analysis/Follow-up
accordions; test-group tables were rendered when evidence existed, while
the no-tests control truthfully had no test table. The user-requested
in-place simplification below now removes Scope and Follow-up from those
same reports. Available excerpts remain escaped and detailed execution
evidence stays in bounded artifacts. Replaced owned reports are
independently confirmed minimized as outdated. Intentional FAILED
verdicts remain red even when publication and cleanup succeed. Missing
iOS result files are unverified execution, not demonstrated flakes or
proof that the target PR is wrong. A passing gate is not full coverage,
a code review, or merge readiness.

#39179's old Windows attempts at sources before `d4397` could not parse
failure-only results because the snapshot-size helper was declared after
that branch exited. The older corrective
[15597112](https://dev.azure.com/DevDiv/DevDiv/_build/results?buildId=15597112)
published and cleaned up successfully but did **not** validate the
helper fix. Final
[15597455](https://dev.azure.com/DevDiv/DevDiv/_build/results?buildId=15597455)
validates the exact helper source and retains the 156,762-byte
`test-failure-HybridWebViewFeatureTests.log`. Its author advanced the
raw reviewed head from `63621b4f8254b5a4112b1dbac3e676633544ca52` to
`0d16b9cc87ef5640e176a2666e02c269ebdd6ce7` before final dispatch; those
identities remain separate. Final reviewed/live head is unchanged, only
the passing gate signal is present, and the lock is absent. The final
build is `partiallySucceeded` because of its initial WSL preparation
warning; protected-base recovery, actual Gate, export, fresh
publication, and cleanup succeeded. Native Windows provisioning at
source `ecd602ef` is separately verified below.

**Canary-exposed corrections:**

- Source `78bb5d3a3bc6da91357b5b116542d77bcc283449`: explicitly exit
successfully after checked publication so an accepted optional
label-removal 404 cannot leak a native exit code into PowerShell@2.
Required API errors still throw. Bound/truncate allowlisted optional
transcripts rather than rejecting all GateLogs when a transcript is
oversized. Select the containing unit fixture instead of broad nested
`Resize` (597 cases became the intended 16). Corrective SKIPPED,
intentional FAILED, and INCONCLUSIVE publications and cleanup complete
successfully.
- Source `d4397eaa8b855209c963ea8aad201508c3d45c05`: move the unchanged
snapshot-size parser helper before shared parsing and both verification
modes; retain bounded `test-failure*.log` diagnostics. Updated related
documentation. PowerShell parsing of both changed scripts and `git diff
--check` passed. `Invoke-Pester -Path
@('.github/skills/verify-tests-fail-without-fix/scripts/Verify-TestsFail.Tests.ps1',
'.github/scripts/shared/Export-ExpectedPRAgentArtifact.Tests.ps1',
'.github/scripts/shared/Copy-BoundedDiagnosticFile.Tests.ps1',
'.github/scripts/shared/Import-ExpectedPRAgentArtifact.Tests.ps1')
-Output Minimal -PassThru` — **141 passed**, zero
failed/skipped/inconclusive/not-run. No new pipeline/configuration tests
were written. Actual Windows failure-only parser/log-export/publication
verification passed in
[15597455](https://dev.azure.com/DevDiv/DevDiv/_build/results?buildId=15597455).
- Source `ecd602ef48662a2a59f083d9db8fc5bdfb83fd45`: select a native
PowerShell child for the Windows MSBuild-task watchdog instead of system
`bash` that selected unconfigured WSL on Windows-2022. Retain the
existing Unix command, wall-clock bound, output sanitization, exit-code
propagation, and retry markers. YAML parsing, all eight embedded
PowerShell blocks, the Windows child command, and `git diff --check`
passed; no pipeline tests were added. The additional [Windows bootstrap
control
15597596](https://dev.azure.com/DevDiv/DevDiv/_build/results?buildId=15597596),
on already-selected no-tests PR #39213 at unchanged head
`1021c9a53afc990312bd6be5cea48dd56205c96f`, **completed successfully at
this exact source**. MSBuild tasks actually built on the first attempt
in 3m10s, with zero errors and no WSL/retry failure. Its bounded report
is SKIPPED; fresh MauiBot
[6038579070](#39213 (comment))
rendering, absence of pass/fail signals, prior-owned minimization,
export, publication, and cleanup are verified. No native tests are
claimed for this control; it is not a substitute for the separate
Windows helper execution.

**User-requested compact presentation at source
`e41058bb0798ed6dddabcb1fda339d532bf2f145`:**

- Remove the Follow-up accordion and its unused next-action logic, the
Scope badge/text, and the report/artifact-link footer. Keep
Result/Platform/Commit badges, Gate analysis, nuanced verdicts, test
tables, escaped excerpts, and pinned head/baseline identities. Update
both relevant report-format documentation sections. Publication
ownership, ordering, labels, minimization, and artifact limits are
unchanged.
- Publisher PowerShell AST parsing and `git diff --cached --check`
passed. Production `Post-PRGate.ps1 -DryRun` and actual GitHub Markdown
rendering passed using retained evidence for full-mode PASSED (#38441),
compile-coupled PASSED (#38625), failure-only PASSED (#39179), FAILED
(#37319), SKIPPED (#39213), and INCONCLUSIVE (#37690). Each has three
badges and closed Gate analysis without Scope, Follow-up, or the footer;
test tables and escaped log contents remain unchanged. No new pipeline
tests or native verification reruns were added.
- All ten report URLs above were updated **in place** with separately
guarded maintainer edits after freshly checking each comment's exact
body, update timestamp, owner, ID, and run marker. The publisher was not
run under the maintainer's identity. Actual stored `body_html` read-back
verifies the same MauiBot comment IDs and unchanged verdicts, commit
identities, test tables, and log text. These are presentation-only edits
of existing evidence, not new Azure Gate runs or new comments.

</details>

The additive correction, remote canary verification, earlier ten-PR
verification, and compact comment presentation are complete and pushed.
This PR remains **draft** while normal CI finishes; no merge readiness
is claimed. The earlier model-policy and skill-harness failures are
preserved above as source-specific evidence, not silently repaired or
described as green. After this PR merges, `/review` continues the full
process and `/review gate` selects only existing-test verification.

### Issues Fixed

<!-- Please make sure that there is a bug logged for the issue being
fixed. The bug should describe the problem and how to reproduce it. -->

N/A - requested additive gate-only review and report-presentation
changes; #38807 is the initial report-layout reference, not an issue
fixed by this PR.

<!--
Are you targeting main? All PRs should target the main branch unless
otherwise noted.
-->

---------

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
kubaflo pushed a commit that referenced this pull request Oct 14, 2026
)

### Description of Change

A `Picker` loses its selection when `SelectedItem` is set before
`ItemsSource`, which is what happens when `SelectedItem` comes first in
XAML:

```xml
<Picker SelectedItem="{Binding Selected}" ItemsSource="{Binding Values}" />  <!-- nothing selected -->
<Picker ItemsSource="{Binding Values}" SelectedItem="{Binding Selected}" />  <!-- works -->
```

Because `SelectedItem` is `TwoWay`, the lost selection is also written
back: `Selected` in the view model becomes `null`.

**Root cause**

1. Setting `SelectedItem` calls `UpdateSelectedIndex`, which looks the
item up in the still-empty `Items` and leaves `SelectedIndex` at -1.
2. Setting `ItemsSource` calls `ResetItems`, which calls
`ClampSelectedIndex(SelectedIndex)`, i.e. `ClampSelectedIndex(-1)`.
3. `ClampSelectedIndex(-1)` calls `UpdateSelectedItem(-1)`, which sets
`SelectedItem` to `null`.

**Fix**

In `ResetItems`, when there's no valid `SelectedIndex` but
`SelectedItem` is set, look the item up in the new `ItemsSource`. This
is how `ResyncItemsAndReconcileSelection` already reconciles the
selection after a collection reset, and it is the `SelectedItem`
counterpart of #35629, which made a `SelectedIndex` set before the items
order-independent.

Unchanged:
- A valid `SelectedIndex` is still used as before. `ResetItems` also
runs when the handler connects and when `ItemDisplayBinding` changes.
- A `SelectedItem` that isn't in `ItemsSource` is still cleared.
- `SelectedIndexChanged` is raised once, the same as when `ItemsSource`
is set first and `SelectedItem` second.

`Picker.cs` is identical on `net11.0`, so the issue is there too.

**Tests**

- `PickerTests` (Core.UnitTests):
  - `SelectedItemSetBeforeItemsSourceIsSelected`
- `SelectedItemBoundBeforeItemsSourceKeepsBoundValue` (bindings applied
in that order; the bound value is kept)
- `SelectedItemNotInItemsSourceSetBeforeItemsSourceIsCleared` (behavior
unchanged)
- `Maui30644` (Xaml.UnitTests, Runtime/XamlC/SourceGen): the reporter's
page, with one picker in each attribute order and compiled bindings.

| | Without fix | With fix |
|---|---|---|
| `PickerTests` | 60 passed, 2 failed | 62 passed |
| `Maui30644` | 3 failed (`SelectedIndex` is -1 for every inflator) | 3
passed |

With the fix, the full suites pass: Controls.Core.UnitTests 5721 passed
/ 30 skipped, and Controls.Xaml.UnitTests 2013 passed / 8 skipped.

### Issues Fixed

Fixes #30644
kubaflo pushed a commit that referenced this pull request Oct 18, 2026
)

### Description of Change

A `Picker` loses its selection when `SelectedItem` is set before
`ItemsSource`, which is what happens when `SelectedItem` comes first in
XAML:

```xml
<Picker SelectedItem="{Binding Selected}" ItemsSource="{Binding Values}" />  <!-- nothing selected -->
<Picker ItemsSource="{Binding Values}" SelectedItem="{Binding Selected}" />  <!-- works -->
```

Because `SelectedItem` is `TwoWay`, the lost selection is also written
back: `Selected` in the view model becomes `null`.

**Root cause**

1. Setting `SelectedItem` calls `UpdateSelectedIndex`, which looks the
item up in the still-empty `Items` and leaves `SelectedIndex` at -1.
2. Setting `ItemsSource` calls `ResetItems`, which calls
`ClampSelectedIndex(SelectedIndex)`, i.e. `ClampSelectedIndex(-1)`.
3. `ClampSelectedIndex(-1)` calls `UpdateSelectedItem(-1)`, which sets
`SelectedItem` to `null`.

**Fix**

In `ResetItems`, when there's no valid `SelectedIndex` but
`SelectedItem` is set, look the item up in the new `ItemsSource`. This
is how `ResyncItemsAndReconcileSelection` already reconciles the
selection after a collection reset, and it is the `SelectedItem`
counterpart of #35629, which made a `SelectedIndex` set before the items
order-independent.

Unchanged:
- A valid `SelectedIndex` is still used as before. `ResetItems` also
runs when the handler connects and when `ItemDisplayBinding` changes.
- A `SelectedItem` that isn't in `ItemsSource` is still cleared.
- `SelectedIndexChanged` is raised once, the same as when `ItemsSource`
is set first and `SelectedItem` second.

`Picker.cs` is identical on `net11.0`, so the issue is there too.

**Tests**

- `PickerTests` (Core.UnitTests):
  - `SelectedItemSetBeforeItemsSourceIsSelected`
- `SelectedItemBoundBeforeItemsSourceKeepsBoundValue` (bindings applied
in that order; the bound value is kept)
- `SelectedItemNotInItemsSourceSetBeforeItemsSourceIsCleared` (behavior
unchanged)
- `Maui30644` (Xaml.UnitTests, Runtime/XamlC/SourceGen): the reporter's
page, with one picker in each attribute order and compiled bindings.

| | Without fix | With fix |
|---|---|---|
| `PickerTests` | 60 passed, 2 failed | 62 passed |
| `Maui30644` | 3 failed (`SelectedIndex` is -1 for every inflator) | 3
passed |

With the fix, the full suites pass: Controls.Core.UnitTests 5721 passed
/ 30 skipped, and Controls.Xaml.UnitTests 2013 passed / 8 skipped.

### Issues Fixed

Fixes #30644
kubaflo pushed a commit that referenced this pull request Oct 21, 2026
)

### Description of Change

A `Picker` loses its selection when `SelectedItem` is set before
`ItemsSource`, which is what happens when `SelectedItem` comes first in
XAML:

```xml
<Picker SelectedItem="{Binding Selected}" ItemsSource="{Binding Values}" />  <!-- nothing selected -->
<Picker ItemsSource="{Binding Values}" SelectedItem="{Binding Selected}" />  <!-- works -->
```

Because `SelectedItem` is `TwoWay`, the lost selection is also written
back: `Selected` in the view model becomes `null`.

**Root cause**

1. Setting `SelectedItem` calls `UpdateSelectedIndex`, which looks the
item up in the still-empty `Items` and leaves `SelectedIndex` at -1.
2. Setting `ItemsSource` calls `ResetItems`, which calls
`ClampSelectedIndex(SelectedIndex)`, i.e. `ClampSelectedIndex(-1)`.
3. `ClampSelectedIndex(-1)` calls `UpdateSelectedItem(-1)`, which sets
`SelectedItem` to `null`.

**Fix**

In `ResetItems`, when there's no valid `SelectedIndex` but
`SelectedItem` is set, look the item up in the new `ItemsSource`. This
is how `ResyncItemsAndReconcileSelection` already reconciles the
selection after a collection reset, and it is the `SelectedItem`
counterpart of #35629, which made a `SelectedIndex` set before the items
order-independent.

Unchanged:
- A valid `SelectedIndex` is still used as before. `ResetItems` also
runs when the handler connects and when `ItemDisplayBinding` changes.
- A `SelectedItem` that isn't in `ItemsSource` is still cleared.
- `SelectedIndexChanged` is raised once, the same as when `ItemsSource`
is set first and `SelectedItem` second.

`Picker.cs` is identical on `net11.0`, so the issue is there too.

**Tests**

- `PickerTests` (Core.UnitTests):
  - `SelectedItemSetBeforeItemsSourceIsSelected`
- `SelectedItemBoundBeforeItemsSourceKeepsBoundValue` (bindings applied
in that order; the bound value is kept)
- `SelectedItemNotInItemsSourceSetBeforeItemsSourceIsCleared` (behavior
unchanged)
- `Maui30644` (Xaml.UnitTests, Runtime/XamlC/SourceGen): the reporter's
page, with one picker in each attribute order and compiled bindings.

| | Without fix | With fix |
|---|---|---|
| `PickerTests` | 60 passed, 2 failed | 62 passed |
| `Maui30644` | 3 failed (`SelectedIndex` is -1 for every inflator) | 3
passed |

With the fix, the full suites pass: Controls.Core.UnitTests 5721 passed
/ 30 skipped, and Controls.Xaml.UnitTests 2013 passed / 8 skipped.

### Issues Fixed

Fixes #30644
kubaflo pushed a commit that referenced this pull request Oct 25, 2026
)

### Description of Change

A `Picker` loses its selection when `SelectedItem` is set before
`ItemsSource`, which is what happens when `SelectedItem` comes first in
XAML:

```xml
<Picker SelectedItem="{Binding Selected}" ItemsSource="{Binding Values}" />  <!-- nothing selected -->
<Picker ItemsSource="{Binding Values}" SelectedItem="{Binding Selected}" />  <!-- works -->
```

Because `SelectedItem` is `TwoWay`, the lost selection is also written
back: `Selected` in the view model becomes `null`.

**Root cause**

1. Setting `SelectedItem` calls `UpdateSelectedIndex`, which looks the
item up in the still-empty `Items` and leaves `SelectedIndex` at -1.
2. Setting `ItemsSource` calls `ResetItems`, which calls
`ClampSelectedIndex(SelectedIndex)`, i.e. `ClampSelectedIndex(-1)`.
3. `ClampSelectedIndex(-1)` calls `UpdateSelectedItem(-1)`, which sets
`SelectedItem` to `null`.

**Fix**

In `ResetItems`, when there's no valid `SelectedIndex` but
`SelectedItem` is set, look the item up in the new `ItemsSource`. This
is how `ResyncItemsAndReconcileSelection` already reconciles the
selection after a collection reset, and it is the `SelectedItem`
counterpart of #35629, which made a `SelectedIndex` set before the items
order-independent.

Unchanged:
- A valid `SelectedIndex` is still used as before. `ResetItems` also
runs when the handler connects and when `ItemDisplayBinding` changes.
- A `SelectedItem` that isn't in `ItemsSource` is still cleared.
- `SelectedIndexChanged` is raised once, the same as when `ItemsSource`
is set first and `SelectedItem` second.

`Picker.cs` is identical on `net11.0`, so the issue is there too.

**Tests**

- `PickerTests` (Core.UnitTests):
  - `SelectedItemSetBeforeItemsSourceIsSelected`
- `SelectedItemBoundBeforeItemsSourceKeepsBoundValue` (bindings applied
in that order; the bound value is kept)
- `SelectedItemNotInItemsSourceSetBeforeItemsSourceIsCleared` (behavior
unchanged)
- `Maui30644` (Xaml.UnitTests, Runtime/XamlC/SourceGen): the reporter's
page, with one picker in each attribute order and compiled bindings.

| | Without fix | With fix |
|---|---|---|
| `PickerTests` | 60 passed, 2 failed | 62 passed |
| `Maui30644` | 3 failed (`SelectedIndex` is -1 for every inflator) | 3
passed |

With the fix, the full suites pass: Controls.Core.UnitTests 5721 passed
/ 30 skipped, and Controls.Xaml.UnitTests 2013 passed / 8 skipped.

### Issues Fixed

Fixes #30644
kubaflo pushed a commit that referenced this pull request Oct 26, 2026
)

### Description of Change

A `Picker` loses its selection when `SelectedItem` is set before
`ItemsSource`, which is what happens when `SelectedItem` comes first in
XAML:

```xml
<Picker SelectedItem="{Binding Selected}" ItemsSource="{Binding Values}" />  <!-- nothing selected -->
<Picker ItemsSource="{Binding Values}" SelectedItem="{Binding Selected}" />  <!-- works -->
```

Because `SelectedItem` is `TwoWay`, the lost selection is also written
back: `Selected` in the view model becomes `null`.

**Root cause**

1. Setting `SelectedItem` calls `UpdateSelectedIndex`, which looks the
item up in the still-empty `Items` and leaves `SelectedIndex` at -1.
2. Setting `ItemsSource` calls `ResetItems`, which calls
`ClampSelectedIndex(SelectedIndex)`, i.e. `ClampSelectedIndex(-1)`.
3. `ClampSelectedIndex(-1)` calls `UpdateSelectedItem(-1)`, which sets
`SelectedItem` to `null`.

**Fix**

In `ResetItems`, when there's no valid `SelectedIndex` but
`SelectedItem` is set, look the item up in the new `ItemsSource`. This
is how `ResyncItemsAndReconcileSelection` already reconciles the
selection after a collection reset, and it is the `SelectedItem`
counterpart of #35629, which made a `SelectedIndex` set before the items
order-independent.

Unchanged:
- A valid `SelectedIndex` is still used as before. `ResetItems` also
runs when the handler connects and when `ItemDisplayBinding` changes.
- A `SelectedItem` that isn't in `ItemsSource` is still cleared.
- `SelectedIndexChanged` is raised once, the same as when `ItemsSource`
is set first and `SelectedItem` second.

`Picker.cs` is identical on `net11.0`, so the issue is there too.

**Tests**

- `PickerTests` (Core.UnitTests):
  - `SelectedItemSetBeforeItemsSourceIsSelected`
- `SelectedItemBoundBeforeItemsSourceKeepsBoundValue` (bindings applied
in that order; the bound value is kept)
- `SelectedItemNotInItemsSourceSetBeforeItemsSourceIsCleared` (behavior
unchanged)
- `Maui30644` (Xaml.UnitTests, Runtime/XamlC/SourceGen): the reporter's
page, with one picker in each attribute order and compiled bindings.

| | Without fix | With fix |
|---|---|---|
| `PickerTests` | 60 passed, 2 failed | 62 passed |
| `Maui30644` | 3 failed (`SelectedIndex` is -1 for every inflator) | 3
passed |

With the fix, the full suites pass: Controls.Core.UnitTests 5721 passed
/ 30 skipped, and Controls.Xaml.UnitTests 2013 passed / 8 skipped.

### Issues Fixed

Fixes #30644
github-actions Bot pushed a commit that referenced this pull request Oct 28, 2026
)

### Description of Change

A `Picker` loses its selection when `SelectedItem` is set before
`ItemsSource`, which is what happens when `SelectedItem` comes first in
XAML:

```xml
<Picker SelectedItem="{Binding Selected}" ItemsSource="{Binding Values}" />  <!-- nothing selected -->
<Picker ItemsSource="{Binding Values}" SelectedItem="{Binding Selected}" />  <!-- works -->
```

Because `SelectedItem` is `TwoWay`, the lost selection is also written
back: `Selected` in the view model becomes `null`.

**Root cause**

1. Setting `SelectedItem` calls `UpdateSelectedIndex`, which looks the
item up in the still-empty `Items` and leaves `SelectedIndex` at -1.
2. Setting `ItemsSource` calls `ResetItems`, which calls
`ClampSelectedIndex(SelectedIndex)`, i.e. `ClampSelectedIndex(-1)`.
3. `ClampSelectedIndex(-1)` calls `UpdateSelectedItem(-1)`, which sets
`SelectedItem` to `null`.

**Fix**

In `ResetItems`, when there's no valid `SelectedIndex` but
`SelectedItem` is set, look the item up in the new `ItemsSource`. This
is how `ResyncItemsAndReconcileSelection` already reconciles the
selection after a collection reset, and it is the `SelectedItem`
counterpart of #35629, which made a `SelectedIndex` set before the items
order-independent.

Unchanged:
- A valid `SelectedIndex` is still used as before. `ResetItems` also
runs when the handler connects and when `ItemDisplayBinding` changes.
- A `SelectedItem` that isn't in `ItemsSource` is still cleared.
- `SelectedIndexChanged` is raised once, the same as when `ItemsSource`
is set first and `SelectedItem` second.

`Picker.cs` is identical on `net11.0`, so the issue is there too.

**Tests**

- `PickerTests` (Core.UnitTests):
  - `SelectedItemSetBeforeItemsSourceIsSelected`
- `SelectedItemBoundBeforeItemsSourceKeepsBoundValue` (bindings applied
in that order; the bound value is kept)
- `SelectedItemNotInItemsSourceSetBeforeItemsSourceIsCleared` (behavior
unchanged)
- `Maui30644` (Xaml.UnitTests, Runtime/XamlC/SourceGen): the reporter's
page, with one picker in each attribute order and compiled bindings.

| | Without fix | With fix |
|---|---|---|
| `PickerTests` | 60 passed, 2 failed | 62 passed |
| `Maui30644` | 3 failed (`SelectedIndex` is -1 for every inflator) | 3
passed |

With the fix, the full suites pass: Controls.Core.UnitTests 5721 passed
/ 30 skipped, and Controls.Xaml.UnitTests 2013 passed / 8 skipped.

### Issues Fixed

Fixes #30644
@github-actions

github-actions Bot commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

The /review tests workflow failed before publishing a report. View the workflow run.

This is an automation failure, not a verdict on the PR tests. Maintainers can retry /review tests after the workflow failure is resolved.

This branch was previously deployed

1 inactive deployment
copilot-pat-pool — c525a6d2 Deployed Oct 6, 2026 by MykhailoDav via conclusion #2237
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

community ✨ Community Contribution s/agent-gate-passed AI verified tests catch the bug (fail without fix, pass with fix) s/agent-review-incomplete AI review did not complete all expected phases 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.

Picker does not select an item when SelectedItem precedes ItemsSource in XAML attributes order

4 participants