Skip to content

[Windows] Fix modal page keyboard focus not shifting to newly opened modal#34212

Merged
jfversluis merged 10 commits intoinflight/currentfrom
fix/modal-keyboard-focus-22938
Mar 5, 2026
Merged

[Windows] Fix modal page keyboard focus not shifting to newly opened modal#34212
jfversluis merged 10 commits intoinflight/currentfrom
fix/modal-keyboard-focus-22938

Conversation

@jfversluis
Copy link
Copy Markdown
Member

@jfversluis jfversluis commented Feb 24, 2026

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!

Description

Fixes #22938 - Modal page keyboard focus not shifting on Windows

When a modal page is pushed via Navigation.PushModalAsync on Windows, keyboard focus stays on the underlying page. This causes:

  1. Enter key activates buttons beneath the modal — a serious UX and accessibility bug
  2. Tab navigation cycles through ALL stacked pages — not just the topmost modal

Root Cause

WindowRootViewContainer (the WinUI Panel that stacks pages) had zero focus management. Pages were layered by z-order but keyboard focus was completely unmanaged.

Fix

Three coordinated changes in WindowRootViewContainer:

  1. IsHitTestVisible toggling — When pushing a modal, sets IsHitTestVisible = false on the underlying page to block pointer/touch input. Restores on pop.

  2. GettingFocus event trap — Registers a GettingFocus handler (with handledEventsToo=true) on the container that intercepts any focus attempt leaving the modal page and redirects it back. This mirrors how WinUI3's ContentDialog implements modal focus trapping.

  3. Focus restorationSetFocusToFirstElement moves focus to the first focusable element in the new top page, with a DispatcherQueue fallback for cases where the visual tree isn't ready.

Critical ordering fix: State (_topPage, focus trap) is updated BEFORE CachedChildren.Remove() because WinUI3 fires GettingFocus synchronously when removing a focused element. Without this, the handler would see stale state pointing to the removed modal.

Testing

  • Device test: ModalPageDisablesHitTestOnUnderlyingPage — verifies IsHitTestVisible toggling
  • Device test: ModalPageFocusTrapsAndRestoresCorrectly — verifies full push/pop cycle
  • UI test: Issue22938 — End-to-end test with semi-transparent modal
  • Unit tests: 69/69 existing modal tests pass
  • Manual testing: Verified with MauiApp1 reproduction app (3 push/pop cycles, buttons functional after each pop)

When a modal page is pushed via PushModalAsync on Windows, keyboard focus
now correctly shifts to the modal page. Previously, focus stayed on the
underlying page, allowing Enter/Tab to activate controls beneath the modal.

The fix modifies WindowRootViewContainer to:
- Set IsHitTestVisible=false on the covered page when a modal is pushed,
  which blocks both pointer and keyboard interaction on its entire subtree
- Move keyboard focus to the first focusable element in the new modal page
  via FocusManager.FindFirstFocusableElement
- Reverse both operations when the modal is popped

Fixes #22938

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot AI review requested due to automatic review settings February 24, 2026 12:52
@jfversluis jfversluis added platform/windows t/a11y Relates to accessibility labels Feb 24, 2026
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Fixes a Windows-specific modal navigation issue where keyboard focus remains on the underlying page after PushModalAsync, allowing Enter/Tab to interact with controls behind the modal.

Changes:

  • Adds focus management and hit-testing changes in the Windows WindowRootViewContainer when pushing/popping pages.
  • Adds a new UI test + HostApp issue page for #22938.
  • Adds a Windows device test asserting IsHitTestVisible toggling for underlying vs modal pages.

Reviewed changes

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

File Description
src/Core/src/Platform/Windows/WindowRootViewContainer.cs Disables hit testing on the covered page and attempts to programmatically move focus to the newly added top page.
src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue22938.cs Adds an Appium/NUnit UI regression test around Enter key behavior with modals.
src/Controls/tests/TestCases.HostApp/Issues/Issue22938.cs Adds the HostApp reproduction page used by the new UI test.
src/Controls/tests/DeviceTests/Elements/Modal/ModalTests.Windows.cs Adds a Windows device test asserting IsHitTestVisible behavior during modal push/pop.

- SetFocusToFirstElement now targets UIElement (not just Control) for
  broader coverage, with page.Focus fallback when no focusable element
  is found
- Reorder modal children so Entry is the first focusable element,
  ensuring focus lands on it rather than CloseModalButton
- Update UI test to wait for ModalEntry and tap CloseModalButton
  explicitly for reliability
- Remove unused variable and using directive from device test

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

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

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

- Unsubscribe OnPageLoadedForFocus in RemovePage to prevent leaks
  when a page is removed before its Loaded event fires
- Use -= before += in TryMoveFocusToPage to prevent duplicate
  subscriptions if called multiple times before page loads

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

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

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

jfversluis and others added 2 commits February 24, 2026 17:20
- Add KeyboardNavigationMode.Cycle on modal to trap Tab cycling within it
- Add KeyboardNavigationMode.Once on underlying page as defense-in-depth
- Properly restore TabFocusNavigation via ClearValue when modal is dismissed
- Only set Cycle mode when covering another page (skip for root page)
- Use semi-transparent modal background in UI test to match real-world
  reproduction (issue #22938 comment, TomRobson-me/KeyboardTabBug repo)
- Add Tab cycling UI test that verifies focus cannot leak to underlying page
- Extend device test to assert TabFocusNavigation properties

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Replace the TabFocusNavigation-based approach with a GettingFocus event
handler that intercepts and redirects focus changes — the same pattern
WinUI3's ContentDialog uses to trap keyboard focus.

This avoids setting IsEnabled=false (which caused a post-pop regression
where buttons stopped responding to clicks) and TabFocusNavigation modes
(which don't actually prevent Tab from entering a subtree from outside).

The new approach:
- IsHitTestVisible=false blocks pointer/touch on covered pages
- GettingFocus handler prevents Tab from reaching underlying pages
- No properties changed on pages that could corrupt WinUI state

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@jfversluis jfversluis marked this pull request as draft February 25, 2026 09:05
jfversluis and others added 3 commits February 25, 2026 10:39
Two fixes for modal focus management:

1. Store GettingFocus handler delegate as a field so RemoveHandler
   can correctly match and remove the handler added by AddHandler.
   Previously, each call created a new delegate instance which could
   cause the handler to leak (never removed) on pop.

2. Add DispatcherQueue fallback in SetFocusToFirstElement - if
   Focus(Programmatic) fails because the visual tree isn't fully
   ready after re-insertion, defer the focus call by one frame.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Critical bug: When CachedChildren.Remove() is called, WinUI3 fires
GettingFocus synchronously because the focused modal element is being
removed. If _topPage still references the removed modal at that point,
OnContainerGettingFocus redirects focus to a detached element or
cancels the focus change, leaving focus in a broken state.

Fix: Update _topPage and disable the focus trap BEFORE removing from
CachedChildren, so the handler sees the correct state if it fires
during removal.

Also adds ModalPageFocusTrapsAndRestoresCorrectly device test.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
- Fix RemovePage to scan for actual page views (WindowRootView) instead of
  using index arithmetic that failed when non-page children (W2DGraphicsView)
  were present in CachedChildren
- Set TabFocusNavigation=Cycle on modal to prevent Tab from escaping to
  underlying pages without relying solely on GettingFocus interception
- Add _modalFocusTrapActive guard in OnContainerGettingFocus for defense-in-depth

Root cause: CachedChildren can contain non-page overlays (e.g., W2DGraphicsView
for visual diagnostics). The old RemovePage used CachedChildren.Count-based
index math that selected the wrong element as newTopPage and failed to disable
the focus trap, leaving the underlying page with IsHitTestVisible=false and
focus interception still active after modal pop.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@jfversluis jfversluis requested a review from Copilot February 25, 2026 16:17
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

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

…test

- Store original TabFocusNavigation value before setting Cycle on modal,
  restore it in RemovePage to prevent stale state if page is reused
- Add NestedModalPagesMaintainHitTestVisibilityAndFocusTrap device test
  covering push A → push B → pop B (A still active) → pop A (root interactive)

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

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 4 out of 4 changed files in this pull request and generated 1 comment.

Preserves the original IsHitTestVisible value before setting it to false
when a modal covers a page. On pop, restores the cached value instead of
unconditionally setting true, so pages with InputTransparent bindings or
other reasons for IsHitTestVisible=false retain their original state.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@jfversluis jfversluis marked this pull request as ready for review February 26, 2026 09:38
Copy link
Copy Markdown
Contributor

@kubaflo kubaflo left a comment

Choose a reason for hiding this comment

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

Detailed Code Review

✅ Architecture & Approach — Excellent

The three-layered defense in WindowRootViewContainer is well-designed:

  1. IsHitTestVisible toggling — blocks pointer/touch to underlying pages
  2. GettingFocus event trap — intercepts keyboard focus escaping the modal (mirrors WinUI3 ContentDialog)
  3. TabFocusNavigation = Cycle — constrains Tab cycling to the modal

The state-save/restore pattern using _originalIsHitTestVisible and _originalTabNavigation dictionaries is clean. The critical ordering fix (updating _topPage BEFORE CachedChildren.Remove()) correctly handles WinUI3's synchronous GettingFocus firing during element removal.

I traced through all code paths (push/pop with transparent vs. opaque backgrounds, nested modals, NavigationRootManager.Connect reconnections) and the logic is correct in all scenarios.


🔴 Issues Found

1. UI Test May Fail on Non-Windows Platforms (Medium-High)

The Issue22938 UI test calls App.SendTabKey() and App.PressEnter() without any platform guard, and the HostApp page uses PlatformAffected.All. These keyboard-focused tests are unreliable on iOS/Android where hardware keyboard focus semantics differ. The Tab cycling test especially — 10 Tab presses on mobile could cause flaky results.

Recommendation: Change PlatformAffected.AllPlatformAffected.Windows in the HostApp page, since this is fundamentally a Windows keyboard focus bug.

2. TrySetNewFocusedElement Return Value Unchecked (Low)

In OnContainerGettingFocus, if TrySetNewFocusedElement returns false, focus could momentarily escape the modal. Consider:

if (!args.TrySetNewFocusedElement(firstFocusable))
    args.TryCancel();

🟡 Suggestions (Non-Blocking)

3. Device Test Coverage Gap: Default Background Modal

All tests use colored/semi-transparent backgrounds. ModalNavigationManager.Windows.cs has a distinct code path where modals with default backgrounds cause RemovePage on the underlying page before AddPage for the modal. A test case with a default-background modal would cover this path.

4. RemovePage Type Check Assumption

The child is not WindowRootView filter in RemovePage works because all AddPage callers pass windowManager.RootView (which is WindowRootView). A brief comment documenting this assumption would help future maintainers.


✅ Test Quality — Good

Test Verdict
ModalPageDisablesHitTestOnUnderlyingPage ✅ Thorough (covers BackgroundColor vs Brush)
ModalPageFocusTrapsAndRestoresCorrectly ✅ Good (full push/pop + container state)
NestedModalPagesMaintainHitTestVisibilityAndFocusTrap ✅ Excellent (2-deep stack, correct unwinding)
Issue22938 UI tests 🟡 Good but needs Windows platform scoping

📝 Summary

Aspect Rating
Correctness ✅ Sound — all push/pop/nested flows verified
Design ✅ Mirrors WinUI3 ContentDialog pattern
State management ✅ Save/restore dictionaries properly managed
Tests 🟡 Good coverage, UI test needs platform scoping
Risk Low — Windows-only, well-contained

Overall this is a well-implemented fix. Main actionable item is scoping the UI test to Windows-only to prevent potential flakiness on mobile platforms.

@kubaflo kubaflo enabled auto-merge (squash) March 2, 2026 13:02
@PureWeen PureWeen modified the milestones: .NET 10 SR5, .NET 10 SR6 Mar 3, 2026
@jfversluis jfversluis changed the base branch from main to inflight/current March 5, 2026 09:33
@jfversluis jfversluis disabled auto-merge March 5, 2026 09:33
@jfversluis jfversluis merged commit 5099f02 into inflight/current Mar 5, 2026
27 checks passed
@jfversluis jfversluis deleted the fix/modal-keyboard-focus-22938 branch March 5, 2026 09:34
PureWeen pushed a commit that referenced this pull request Mar 11, 2026
…modal (#34212)

> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could <a
href="https://github.com/dotnet/maui/wiki/Testing-PR-Builds">test the
resulting artifacts</a> from this PR and let us know in a comment if
this change resolves your issue. Thank you!

## Description

Fixes #22938 - Modal page keyboard focus not shifting on Windows

When a modal page is pushed via `Navigation.PushModalAsync` on Windows,
keyboard focus stays on the underlying page. This causes:
1. **Enter key activates buttons beneath the modal** — a serious UX and
accessibility bug
2. **Tab navigation cycles through ALL stacked pages** — not just the
topmost modal

### Root Cause

`WindowRootViewContainer` (the WinUI Panel that stacks pages) had **zero
focus management**. Pages were layered by z-order but keyboard focus was
completely unmanaged.

### Fix

Three coordinated changes in `WindowRootViewContainer`:

1. **IsHitTestVisible toggling** — When pushing a modal, sets
`IsHitTestVisible = false` on the underlying page to block pointer/touch
input. Restores on pop.

2. **GettingFocus event trap** — Registers a `GettingFocus` handler
(with `handledEventsToo=true`) on the container that intercepts any
focus attempt leaving the modal page and redirects it back. This mirrors
how WinUI3's `ContentDialog` implements modal focus trapping.

3. **Focus restoration** — `SetFocusToFirstElement` moves focus to the
first focusable element in the new top page, with a `DispatcherQueue`
fallback for cases where the visual tree isn't ready.

**Critical ordering fix**: State (`_topPage`, focus trap) is updated
BEFORE `CachedChildren.Remove()` because WinUI3 fires `GettingFocus`
synchronously when removing a focused element. Without this, the handler
would see stale state pointing to the removed modal.

### Testing

- **Device test**: `ModalPageDisablesHitTestOnUnderlyingPage` — verifies
IsHitTestVisible toggling
- **Device test**: `ModalPageFocusTrapsAndRestoresCorrectly` — verifies
full push/pop cycle
- **UI test**: `Issue22938` — End-to-end test with semi-transparent
modal
- **Unit tests**: 69/69 existing modal tests pass
- **Manual testing**: Verified with MauiApp1 reproduction app (3
push/pop cycles, buttons functional after each pop)

---------

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
github-actions bot pushed a commit that referenced this pull request Mar 11, 2026
…modal (#34212)

> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could <a
href="https://github.com/dotnet/maui/wiki/Testing-PR-Builds">test the
resulting artifacts</a> from this PR and let us know in a comment if
this change resolves your issue. Thank you!

## Description

Fixes #22938 - Modal page keyboard focus not shifting on Windows

When a modal page is pushed via `Navigation.PushModalAsync` on Windows,
keyboard focus stays on the underlying page. This causes:
1. **Enter key activates buttons beneath the modal** — a serious UX and
accessibility bug
2. **Tab navigation cycles through ALL stacked pages** — not just the
topmost modal

### Root Cause

`WindowRootViewContainer` (the WinUI Panel that stacks pages) had **zero
focus management**. Pages were layered by z-order but keyboard focus was
completely unmanaged.

### Fix

Three coordinated changes in `WindowRootViewContainer`:

1. **IsHitTestVisible toggling** — When pushing a modal, sets
`IsHitTestVisible = false` on the underlying page to block pointer/touch
input. Restores on pop.

2. **GettingFocus event trap** — Registers a `GettingFocus` handler
(with `handledEventsToo=true`) on the container that intercepts any
focus attempt leaving the modal page and redirects it back. This mirrors
how WinUI3's `ContentDialog` implements modal focus trapping.

3. **Focus restoration** — `SetFocusToFirstElement` moves focus to the
first focusable element in the new top page, with a `DispatcherQueue`
fallback for cases where the visual tree isn't ready.

**Critical ordering fix**: State (`_topPage`, focus trap) is updated
BEFORE `CachedChildren.Remove()` because WinUI3 fires `GettingFocus`
synchronously when removing a focused element. Without this, the handler
would see stale state pointing to the removed modal.

### Testing

- **Device test**: `ModalPageDisablesHitTestOnUnderlyingPage` — verifies
IsHitTestVisible toggling
- **Device test**: `ModalPageFocusTrapsAndRestoresCorrectly` — verifies
full push/pop cycle
- **UI test**: `Issue22938` — End-to-end test with semi-transparent
modal
- **Unit tests**: 69/69 existing modal tests pass
- **Manual testing**: Verified with MauiApp1 reproduction app (3
push/pop cycles, buttons functional after each pop)

---------

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@PureWeen PureWeen mentioned this pull request Mar 17, 2026
PureWeen pushed a commit that referenced this pull request Mar 19, 2026
…modal (#34212)

> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could <a
href="https://github.com/dotnet/maui/wiki/Testing-PR-Builds">test the
resulting artifacts</a> from this PR and let us know in a comment if
this change resolves your issue. Thank you!

## Description

Fixes #22938 - Modal page keyboard focus not shifting on Windows

When a modal page is pushed via `Navigation.PushModalAsync` on Windows,
keyboard focus stays on the underlying page. This causes:
1. **Enter key activates buttons beneath the modal** — a serious UX and
accessibility bug
2. **Tab navigation cycles through ALL stacked pages** — not just the
topmost modal

### Root Cause

`WindowRootViewContainer` (the WinUI Panel that stacks pages) had **zero
focus management**. Pages were layered by z-order but keyboard focus was
completely unmanaged.

### Fix

Three coordinated changes in `WindowRootViewContainer`:

1. **IsHitTestVisible toggling** — When pushing a modal, sets
`IsHitTestVisible = false` on the underlying page to block pointer/touch
input. Restores on pop.

2. **GettingFocus event trap** — Registers a `GettingFocus` handler
(with `handledEventsToo=true`) on the container that intercepts any
focus attempt leaving the modal page and redirects it back. This mirrors
how WinUI3's `ContentDialog` implements modal focus trapping.

3. **Focus restoration** — `SetFocusToFirstElement` moves focus to the
first focusable element in the new top page, with a `DispatcherQueue`
fallback for cases where the visual tree isn't ready.

**Critical ordering fix**: State (`_topPage`, focus trap) is updated
BEFORE `CachedChildren.Remove()` because WinUI3 fires `GettingFocus`
synchronously when removing a focused element. Without this, the handler
would see stale state pointing to the removed modal.

### Testing

- **Device test**: `ModalPageDisablesHitTestOnUnderlyingPage` — verifies
IsHitTestVisible toggling
- **Device test**: `ModalPageFocusTrapsAndRestoresCorrectly` — verifies
full push/pop cycle
- **UI test**: `Issue22938` — End-to-end test with semi-transparent
modal
- **Unit tests**: 69/69 existing modal tests pass
- **Manual testing**: Verified with MauiApp1 reproduction app (3
push/pop cycles, buttons functional after each pop)

---------

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
github-actions bot pushed a commit that referenced this pull request Mar 20, 2026
…modal (#34212)

> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could <a
href="https://github.com/dotnet/maui/wiki/Testing-PR-Builds">test the
resulting artifacts</a> from this PR and let us know in a comment if
this change resolves your issue. Thank you!

## Description

Fixes #22938 - Modal page keyboard focus not shifting on Windows

When a modal page is pushed via `Navigation.PushModalAsync` on Windows,
keyboard focus stays on the underlying page. This causes:
1. **Enter key activates buttons beneath the modal** — a serious UX and
accessibility bug
2. **Tab navigation cycles through ALL stacked pages** — not just the
topmost modal

### Root Cause

`WindowRootViewContainer` (the WinUI Panel that stacks pages) had **zero
focus management**. Pages were layered by z-order but keyboard focus was
completely unmanaged.

### Fix

Three coordinated changes in `WindowRootViewContainer`:

1. **IsHitTestVisible toggling** — When pushing a modal, sets
`IsHitTestVisible = false` on the underlying page to block pointer/touch
input. Restores on pop.

2. **GettingFocus event trap** — Registers a `GettingFocus` handler
(with `handledEventsToo=true`) on the container that intercepts any
focus attempt leaving the modal page and redirects it back. This mirrors
how WinUI3's `ContentDialog` implements modal focus trapping.

3. **Focus restoration** — `SetFocusToFirstElement` moves focus to the
first focusable element in the new top page, with a `DispatcherQueue`
fallback for cases where the visual tree isn't ready.

**Critical ordering fix**: State (`_topPage`, focus trap) is updated
BEFORE `CachedChildren.Remove()` because WinUI3 fires `GettingFocus`
synchronously when removing a focused element. Without this, the handler
would see stale state pointing to the removed modal.

### Testing

- **Device test**: `ModalPageDisablesHitTestOnUnderlyingPage` — verifies
IsHitTestVisible toggling
- **Device test**: `ModalPageFocusTrapsAndRestoresCorrectly` — verifies
full push/pop cycle
- **UI test**: `Issue22938` — End-to-end test with semi-transparent
modal
- **Unit tests**: 69/69 existing modal tests pass
- **Manual testing**: Verified with MauiApp1 reproduction app (3
push/pop cycles, buttons functional after each pop)

---------

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
github-actions bot pushed a commit that referenced this pull request Mar 22, 2026
…modal (#34212)

> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could <a
href="https://github.com/dotnet/maui/wiki/Testing-PR-Builds">test the
resulting artifacts</a> from this PR and let us know in a comment if
this change resolves your issue. Thank you!

## Description

Fixes #22938 - Modal page keyboard focus not shifting on Windows

When a modal page is pushed via `Navigation.PushModalAsync` on Windows,
keyboard focus stays on the underlying page. This causes:
1. **Enter key activates buttons beneath the modal** — a serious UX and
accessibility bug
2. **Tab navigation cycles through ALL stacked pages** — not just the
topmost modal

### Root Cause

`WindowRootViewContainer` (the WinUI Panel that stacks pages) had **zero
focus management**. Pages were layered by z-order but keyboard focus was
completely unmanaged.

### Fix

Three coordinated changes in `WindowRootViewContainer`:

1. **IsHitTestVisible toggling** — When pushing a modal, sets
`IsHitTestVisible = false` on the underlying page to block pointer/touch
input. Restores on pop.

2. **GettingFocus event trap** — Registers a `GettingFocus` handler
(with `handledEventsToo=true`) on the container that intercepts any
focus attempt leaving the modal page and redirects it back. This mirrors
how WinUI3's `ContentDialog` implements modal focus trapping.

3. **Focus restoration** — `SetFocusToFirstElement` moves focus to the
first focusable element in the new top page, with a `DispatcherQueue`
fallback for cases where the visual tree isn't ready.

**Critical ordering fix**: State (`_topPage`, focus trap) is updated
BEFORE `CachedChildren.Remove()` because WinUI3 fires `GettingFocus`
synchronously when removing a focused element. Without this, the handler
would see stale state pointing to the removed modal.

### Testing

- **Device test**: `ModalPageDisablesHitTestOnUnderlyingPage` — verifies
IsHitTestVisible toggling
- **Device test**: `ModalPageFocusTrapsAndRestoresCorrectly` — verifies
full push/pop cycle
- **UI test**: `Issue22938` — End-to-end test with semi-transparent
modal
- **Unit tests**: 69/69 existing modal tests pass
- **Manual testing**: Verified with MauiApp1 reproduction app (3
push/pop cycles, buttons functional after each pop)

---------

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
PureWeen added a commit that referenced this pull request Mar 24, 2026
## What's Coming

.NET MAUI inflight/candidate introduces significant improvements across
all platforms with focus on quality, performance, and developer
experience. This release includes 66 commits with various improvements,
bug fixes, and enhancements.


## Activityindicator
- [Android] Implemented material3 support for ActivityIndicator by
@Dhivya-SF4094 in #33481
  <details>
  <summary>🔧 Fixes</summary>

- [Implement material3 support for
ActivityIndicator](#33479)
  </details>

- [iOS] Fix: ActivityIndicator IsRunning ignores IsVisible when set to
true by @bhavanesh2001 in #28983
  <details>
  <summary>🔧 Fixes</summary>

- [[iOS] [ActivityIndicator] `IsRunning` ignores `IsVisible` when set to
`true`](#28968)
  </details>

## Button
- [iOS] Button RTL text and image overlap - fix by @kubaflo in
#29041

## Checkbox
- [iOS/MacCatalyst] Fix CheckBox foreground color not resetting when set
to null by @Ahamed-Ali in #34284
  <details>
  <summary>🔧 Fixes</summary>

- [[iOS] Color of the checkBox control is not properly worked on dynamic
scenarios](#34278)
  </details>

## CollectionView
- [iOS] Fix: CollectionView does not clear selection when SelectedItem
is set to null by @Tamilarasan-Paranthaman in
#30420
  <details>
  <summary>🔧 Fixes</summary>

- [CollectionView not being able to remove selected item highlight on
iOS](#30363)
- [[MAUI] Select items traces are
preserved](#26187)
  </details>

- [iOS] CV2 ItemsLayout update by @kubaflo in
#28675
  <details>
  <summary>🔧 Fixes</summary>

- [CollectionView CollectionViewHandler2 doesnt change ItemsLayout on
DataTrigger](#28656)
- [iOS CollectionView doesn't respect a change to ItemsLayout when using
Items2.CollectionViewHandler2](#31259)
  </details>

- [iOS][CV2] Fix CollectionView renders large empty space at bottom of
view by @devanathan-vaithiyanathan in
#31215
  <details>
  <summary>🔧 Fixes</summary>

- [[iOS] [MacCatalyst] CollectionView renders large empty space at
bottom of view](#17799)
- [[iOS/Mac] CollectionView2 EmptyView takes up large horizontal space
even when the content is
small](#33201)
  </details>

- [iOS] Fixed issue where group Header/Footer template was set to all
items when IsGrouped was true for an ObservableCollection by
@Tamilarasan-Paranthaman in #29144
  <details>
  <summary>🔧 Fixes</summary>

- [[iOS] Group Header/Footer Repeated for All Items When IsGrouped is
True for ObservableCollection in
CollectionView](#29141)
  </details>

- [Android] Fix CollectionView selection crash with HeaderTemplate by
@NirmalKumarYuvaraj in #34275
  <details>
  <summary>🔧 Fixes</summary>

- [[Bug] [Android] System.ArgumentOutOfRangeException: Index was out of
range. Must be non-negative and less than the size of the collection.
Parameter name: index](#34247)
  </details>

## DateTimePicker
- [iOS] Fix TimePicker AM/PM frequently changes when the app is closed
and reopened by @devanathan-vaithiyanathan in
#31066
  <details>
  <summary>🔧 Fixes</summary>

- [[iOS] TimePicker AM/PM frequently changes when the app is closed and
reopened](#30837)
- [Maui 10 iOS TimePicker Strange Characters in place of
AM/PM](#33722)
  </details>

- Android TimePicker ignores 24 hour system setting when using Format
Property - fix by @kubaflo in #28797
  <details>
  <summary>🔧 Fixes</summary>

- [Android TimePicker ignores 24 hour system setting when using Format
Property](#28784)
  </details>

## Drawing
- [iOS, Mac, Windows] GraphicsView: Fix Background/BackgroundColor not
updating by @NirmalKumarYuvaraj in
#31254
  <details>
  <summary>🔧 Fixes</summary>

- [[iOS, Mac, Windows] GraphicsView does not change the
Background/BackgroundColor](#31239)
  </details>

- [iOS] GraphicsView DrawString - fix by @kubaflo in
#26304
  <details>
  <summary>🔧 Fixes</summary>

- [DrawString not rendering in
iOS.](#24450)
- [GraphicsView DrawString not rendering in
iOS](#8486)
- [DrawString doesn't work on
maccatalyst](#4993)
  </details>

- [Android] - Fix Shadow Rendering For Transparent Fill, Stroke (Lines),
and Text on Shapes by @prakashKannanSf3972 in
#29528
  <details>
  <summary>🔧 Fixes</summary>

- [Ellipse Transparency Not Rendered When Drawing Arc Inside the Ellipse
Using GraphicsView on
Android](#29394)
  </details>

- Revert "[iOS, Mac, Windows] GraphicsView: Fix
Background/BackgroundColor not updating (#31254)" by @Ahamed-Ali via
@Copilot in #34508

## Entry
- [iOS 26] Fix Entry MaxLength not enforced due to new multi-range
delegate by @kubaflo in #32045
  <details>
  <summary>🔧 Fixes</summary>

- [iOS 26 - The MaxLength property value is not respected on an Entry
control.](#32016)
- [.NET MAUI Entry Maximum Length not working on iOS and
macOS](#33316)
  </details>

- [iOS] Fixed Entry with IsPassword toggling loses previously entered
text by @SubhikshaSf4851 in #30572
  <details>
  <summary>🔧 Fixes</summary>

- [Entry with IsPassword toggling loses previously entered text on iOS
when IsPassword is
re-enabled](#30085)
  </details>

## Essentials
- Fix for FilePicker PickMultipleAsync nullable reference type by
@SuthiYuvaraj in #33163
  <details>
  <summary>🔧 Fixes</summary>

- [FilePicker PickMultipleAsync nullable reference
type](#33114)
  </details>

- Replace deprecated NetworkReachability with NWPathMonitor on iOS/macOS
by @jfversluis via @Copilot in #32354
  <details>
  <summary>🔧 Fixes</summary>

- [NetworkReachability is obsolete on iOS/maccatalyst
17.4+](#32312)
- [Use NWPathMonitor on iOS for Essentials
Connectivity](#2574)
  </details>

## Essentials Connectivity
- Update Android Connectivity implementation to use modern APIs by
@jfversluis via @Copilot in #30348
  <details>
  <summary>🔧 Fixes</summary>

- [Update the Android Connectivity implementation to user modern
APIs](#30347)
  </details>

## Flyout
- [iOS] Fixed Flyout icon not updating when root page changes using
InsertPageBefore by @Vignesh-SF3580 in
#29924
  <details>
  <summary>🔧 Fixes</summary>

- [[iOS] Flyout icon not replaced by back button when root page is
changed using
InsertPageBefore](#29921)
  </details>

## Flyoutpage
- [iOS] Flyout Items Not Displayed in RightToLeft FlowDirection in
Landscape - fix by @kubaflo in #26762
  <details>
  <summary>🔧 Fixes</summary>

- [Flyout Items Not Displayed in RightToLeft FlowDirection on iOS in
Landscape Orientation and Hamburger Icon Positioned
Incorrectly](#26726)
  </details>

## Image
- [Android] Implemented Material3 support for Image by @Dhivya-SF4094 in
#33661
  <details>
  <summary>🔧 Fixes</summary>

- [Implement Material3 support for
Image](#33660)
  </details>

## Keyboard
- [iOS] Fix gap at top of view after rotating device while Entry
keyboard is visible by @praveenkumarkarunanithi in
#34328
  <details>
  <summary>🔧 Fixes</summary>

- [Focusing and entering texts on entry control causes a gap at the top
after rotating simulator.](#33407)
  </details>

## Label
- [Android] Support for images inside HTML label by @kubaflo in
#21679
  <details>
  <summary>🔧 Fixes</summary>

- [Label with HTML TextType does not display images on
Android](#21044)
  </details>

- [fix] ContentLabel Moved to a nested class to prevent CS0122 in
external source generators by @SubhikshaSf4851 in
#34514
  <details>
  <summary>🔧 Fixes</summary>

- [[MAUI] Building Maui App with sample content results CS0122
errors.](#34512)
  </details>

## Layout
- Optimize ordering of children in Flex layout by @symbiogenesis in
#21961

- [Android] Fix control size properties not available during Loaded
event by @Vignesh-SF3580 in #31590
  <details>
  <summary>🔧 Fixes</summary>

- [CollectionView on Android does not provide height, width, logical
children once loaded, works fine on
Windows](#14364)
- [Control's Loaded event invokes before calling its measure override
method.](#14160)
  </details>

## Mediapicker
- [iOS/Android] MediaPicker: Fix image orientation when RotateImage=true
by @michalpobuta in #33892
  <details>
  <summary>🔧 Fixes</summary>

- [MediaPicker.PickPhotosAsync does not preserve image
orientation](#32650)
  </details>

## Modal
- [Windows] Fix modal page keyboard focus not shifting to newly opened
modal by @jfversluis in #34212
  <details>
  <summary>🔧 Fixes</summary>

- [Keyboard focus does not shift to a newly opened modal page: Pressing
enter clicks the button on the page beneath the modal
page](#22938)
  </details>

## Navigation
- [iOS26] Apply view margins in title view by @kubaflo in
#32205
  <details>
  <summary>🔧 Fixes</summary>

- [NavigationPage TitleView iOS
26](#32200)
  </details>

- [iOS] System.NullReferenceException at
NavigationRenderer.SetStatusBarStyle() by @kubaflo in
#29564
  <details>
  <summary>🔧 Fixes</summary>

- [System.NullReferenceException at
NavigationRenderer.SetStatusBarStyle()](#29535)
  </details>

- [iOS 26] Fix back button color not applied for NavigationPage by
@Shalini-Ashokan in #34326
  <details>
  <summary>🔧 Fixes</summary>

- [[iOS] Color not applied to the Back button text or image on iOS
26](#33966)
  </details>

## Picker
- Fix Picker layout on Mac Catalyst 26+ by @kubaflo in
#33146
  <details>
  <summary>🔧 Fixes</summary>

- [[MacOS 26] Text on picker options are not centered on macOS
26.1](#33229)
  </details>

## Progressbar
- [Android] Implemented Material3 support for ProgressBar by
@SyedAbdulAzeemSF4852 in #33926
  <details>
  <summary>🔧 Fixes</summary>

- [Implement Material3 support for
Progressbar](#33925)
  </details>

## RadioButton
- [iOS, Mac] Fix for RadioButton TextColor for plain Content not working
by @HarishwaranVijayakumar in #31940
  <details>
  <summary>🔧 Fixes</summary>

- [RadioButton: TextColor for plain Content not working on
iOS](#18011)
  </details>

- [All Platforms] Fix RadioButton warning when ControlTemplate is set
with View content by @kubaflo in
#33839
  <details>
  <summary>🔧 Fixes</summary>

- [Seeking clarification on RadioButton + ControlTemplate + Content
documentation](#33829)
  </details>

- Visual state change for disabled RadioButton by @kubaflo in
#23471
  <details>
  <summary>🔧 Fixes</summary>

- [RadioButton disabled UI issue -
iOS](#18668)
  </details>

## SafeArea
- [Android] Fix for TabbedPage BottomNavigation BarBackgroundColor not
extending to system navigation bar by @praveenkumarkarunanithi in
#33428
  <details>
  <summary>🔧 Fixes</summary>

- [[Android] TabbedPage BottomNavigation BarBackgroundColor does not
extend to system navigation bar area in Edge-to-Edge
mode](#33344)
  </details>

## ScrollView
- [Android] ScrollView: Fix HorizontalScrollBarVisibility not updating
immediately at runtime by @SubhikshaSf4851 in
#33528
  <details>
  <summary>🔧 Fixes</summary>

- [Runtime Scrollbar visibility not updating correctly on Android and
macOS platforms.](#33400)
  </details>

- Fixed crash when calling ItemsView.ScrollTo on unloaded CollectionView
by @kubaflo in #25444
  <details>
  <summary>🔧 Fixes</summary>

- [App crashes when calling ItemsView.ScrollTo on unloaded
CollectionView](#23014)
  </details>

## Shell
- [Shell] Update logic for iOS large title display in ShellItemRenderer
by @kubaflo in #33246

- [iOS][Shell] Fix navigation lifecycle and back button for More tab (>5
tabs) by @kubaflo in #27932
  <details>
  <summary>🔧 Fixes</summary>

- [OnAppearing and OnNavigatedTo does not work when using extended
Tabbar (tabbar with more than 5 tabs) on
IOS.](#27799)
- [Shell.BackButtonBehavior does not work when using extended Tabbar
(tabbar with more than 5 tabs)on
IOS.](#27800)
- [Shell TabBar More button causes ViewModel command binding
disconnection on back
navigation](#30862)
- [Content page onappearing not firing if tabs are on the more tab on
IOS](#31166)
  </details>

- [iOS 26] Fix tab bar ghosting when navigating from modal to tabbed
Shell content by @SubhikshaSf4851 in
#34254
  <details>
  <summary>🔧 Fixes</summary>

- [[iOS] Tab bar ghosting issue on iOS 26 (liquid
glass)](#34143)
  </details>

- Fix for Shell tab visibility not updating when navigating back
multiple pages by @BagavathiPerumal in
#34403
  <details>
  <summary>🔧 Fixes</summary>

- [Changing Shell Tab Visibility when navigating back multiple pages
ignores Shell Tab
Visibility](#33351)
  </details>

- [iOS/Mac] Fixed OnBackButtonPressed not firing for Shell Navigation
Bar Button by @Dhivya-SF4094 in
#34401
  <details>
  <summary>🔧 Fixes</summary>

- [[iOS] OnBackButtonPressed not firing for Shell Navigation Bar
button](#34190)
  </details>

## Slider
- [iOS] Fix for Slider ThumbImageSource is not centered properly on iOS
26 by @HarishwaranVijayakumar in
#34019
  <details>
  <summary>🔧 Fixes</summary>

- [[iOS 26] Slider ThumbImageSource is not centered
properly](#33967)
  </details>

- [Android] Fix improper rendering of ThumbimageSource in Slider by
@NirmalKumarYuvaraj in #34064
  <details>
  <summary>🔧 Fixes</summary>

- [[Slider] MAUI Slider thumb image is big on
android](#13258)
  </details>

## Stepper
- [iOS] Fix Stepper layout overlap in landscape on iOS 26 by
@Vignesh-SF3580 in #34325
  <details>
  <summary>🔧 Fixes</summary>

- [[.NET10] D10 - Customize cursor position - Rotating simulator makes
the button and label
overlap](#34273)
  </details>

## SwipeView
- [iOS] SwipeView: Honor FontImageSource.Color in SwipeItem icon by
@kubaflo in #27389
  <details>
  <summary>🔧 Fixes</summary>

- [[iOS] SwipeView: SwipeItem.IconImageSource.FontImageSource color
value not honored](#27377)
  </details>

## Switch
- [Android] Fix Switch thumb shadow missing when ThumbColor is set by
@Shalini-Ashokan in #33960
  <details>
  <summary>🔧 Fixes</summary>

- [Android Switch Control Thumb
Shadow](#19676)
  </details>

## Toolbar
- [iOS/Mac Catalyst 26] Fix Shell.ForegroundColor not applied to
ToolbarItems by @SyedAbdulAzeemSF4852 in
#34085
  <details>
  <summary>🔧 Fixes</summary>

- [[iOS26] Shell.ForegroundColor is not applied to
ToolbarItems](#34083)
  </details>

- [Android] VoiceOver on Toolbar Item by @kubaflo in
#29596
  <details>
  <summary>🔧 Fixes</summary>

- [VoiceOver on Toolbar
Item](#29573)
- [SemanticProperties do not work on
ToolbarItems](#23623)
  </details>


<details>
<summary>🧪 Testing (11)</summary>

- [Testing] Additional Feature Matrix Test Cases for CollectionView by
@TamilarasanSF4853 in #32432
- [Testing] Feature Matrix UITest Cases for VisualStateManager by
@LogishaSelvarajSF4525 in #34146
- [Testing] Feature Matrix UITest Cases for Clip by @TamilarasanSF4853
in #34121
- [Testing] Feature matrix UITest Cases for Map Control by
@HarishKumarSF4517 in #31656
- [Testing] Feature matrix UITest Cases for Visual Transform Control by
@HarishKumarSF4517 in #32799
- [Testing] Feature Matrix UITest Cases for Shell Pages by
@NafeelaNazhir in #33945
- [Testing] Feature Matrix UITest Cases for Triggers by
@HarishKumarSF4517 in #34152
- [Testing] Refactoring Feature Matrix UITest Cases for CheckBox Control
by @LogishaSelvarajSF4525 in #34283
- Resolve UI test Build Sample failures - Candidate March 16 by
@Ahamed-Ali in #34442
- Fix the failures in the Candidate branch- March 16 by @Ahamed-Ali in
#34453
  <details>
  <summary>🔧 Fixes</summary>

  - [March 16th, Candidate](#34437)
  </details>
- Fixed the iOS 18.5 Candidate failures (March 16,2026) by @Ahamed-Ali
in #34593
  <details>
  <summary>🔧 Fixes</summary>

  - [March 16th, Candidate](#34437)
  </details>

</details>

<details>
<summary>📦 Other (2)</summary>

- Fixed candidate test failures caused by PR #33428. by @Ahamed-Ali in
#34515
  <details>
  <summary>🔧 Fixes</summary>

- [[.NET10] On Android, there's a big space at the top for I, M and N2 &
N3](#34509)
  </details>
- Revert "[iOS] Button RTL text and image overlap - fix (#29041)" in
b0497af

</details>

<details>
<summary>📝 Issue References</summary>

Fixes #2574, Fixes #4993, Fixes #8486, Fixes #13258, Fixes #14160, Fixes
#14364, Fixes #17799, Fixes #18011, Fixes #18668, Fixes #19676, Fixes
#21044, Fixes #22938, Fixes #23014, Fixes #23623, Fixes #24450, Fixes
#26187, Fixes #26726, Fixes #27377, Fixes #27799, Fixes #27800, Fixes
#28656, Fixes #28784, Fixes #28968, Fixes #29141, Fixes #29394, Fixes
#29535, Fixes #29573, Fixes #29921, Fixes #30085, Fixes #30347, Fixes
#30363, Fixes #30837, Fixes #30862, Fixes #31166, Fixes #31239, Fixes
#31259, Fixes #32016, Fixes #32200, Fixes #32312, Fixes #32650, Fixes
#33114, Fixes #33201, Fixes #33229, Fixes #33316, Fixes #33344, Fixes
#33351, Fixes #33400, Fixes #33407, Fixes #33479, Fixes #33660, Fixes
#33722, Fixes #33829, Fixes #33925, Fixes #33966, Fixes #33967, Fixes
#34083, Fixes #34143, Fixes #34190, Fixes #34247, Fixes #34273, Fixes
#34278, Fixes #34437, Fixes #34509, Fixes #34512

</details>

**Full Changelog**:
main...inflight/candidate
KarthikRajaKalaimani pushed a commit to KarthikRajaKalaimani/maui that referenced this pull request Mar 30, 2026
…modal (dotnet#34212)

> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could <a
href="https://github.com/dotnet/maui/wiki/Testing-PR-Builds">test the
resulting artifacts</a> from this PR and let us know in a comment if
this change resolves your issue. Thank you!

## Description

Fixes dotnet#22938 - Modal page keyboard focus not shifting on Windows

When a modal page is pushed via `Navigation.PushModalAsync` on Windows,
keyboard focus stays on the underlying page. This causes:
1. **Enter key activates buttons beneath the modal** — a serious UX and
accessibility bug
2. **Tab navigation cycles through ALL stacked pages** — not just the
topmost modal

### Root Cause

`WindowRootViewContainer` (the WinUI Panel that stacks pages) had **zero
focus management**. Pages were layered by z-order but keyboard focus was
completely unmanaged.

### Fix

Three coordinated changes in `WindowRootViewContainer`:

1. **IsHitTestVisible toggling** — When pushing a modal, sets
`IsHitTestVisible = false` on the underlying page to block pointer/touch
input. Restores on pop.

2. **GettingFocus event trap** — Registers a `GettingFocus` handler
(with `handledEventsToo=true`) on the container that intercepts any
focus attempt leaving the modal page and redirects it back. This mirrors
how WinUI3's `ContentDialog` implements modal focus trapping.

3. **Focus restoration** — `SetFocusToFirstElement` moves focus to the
first focusable element in the new top page, with a `DispatcherQueue`
fallback for cases where the visual tree isn't ready.

**Critical ordering fix**: State (`_topPage`, focus trap) is updated
BEFORE `CachedChildren.Remove()` because WinUI3 fires `GettingFocus`
synchronously when removing a focused element. Without this, the handler
would see stale state pointing to the removed modal.

### Testing

- **Device test**: `ModalPageDisablesHitTestOnUnderlyingPage` — verifies
IsHitTestVisible toggling
- **Device test**: `ModalPageFocusTrapsAndRestoresCorrectly` — verifies
full push/pop cycle
- **UI test**: `Issue22938` — End-to-end test with semi-transparent
modal
- **Unit tests**: 69/69 existing modal tests pass
- **Manual testing**: Verified with MauiApp1 reproduction app (3
push/pop cycles, buttons functional after each pop)

---------

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@github-actions github-actions bot locked and limited conversation to collaborators Apr 5, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

platform/windows t/a11y Relates to accessibility

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Keyboard focus does not shift to a newly opened modal page: Pressing enter clicks the button on the page beneath the modal page

4 participants