Repository navigation
[Windows] Fix COMException when changing Image BackgroundColor via binding after navigation - #36747
Conversation
|
🚀 Dogfood this PR with:
curl -fsSL https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.sh | bash -s -- 36747Or
iex "& { $(irm https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.ps1) } 36747" |
|
Azure Pipelines: Successfully started running 1 pipeline(s). There may be pipelines that require an authorized user to comment /azp run to run. |
|
Azure Pipelines: Successfully started running 1 pipeline(s). There may be pipelines that require an authorized user to comment /azp run to run. |
There was a problem hiding this comment.
Pull request overview
Fixes a Windows-specific crash where changing an Image background via binding after navigating away triggers WinUI visual-tree manipulation and throws a COMException. The approach defers container creation/background application until the native Image is loaded again, and adds an end-to-end UI test + HostApp reproduction page for issue #36694.
Changes:
- Windows: Defer
Imagebackground mapping/container creation untilPlatformView.IsLoaded, and re-apply background onLoaded. - Tests: Add HostApp reproduction scenario for issue 36694 (navigation + binding update while previous page is unloaded).
- Tests: Add Appium UITest covering the navigation + background change scenario to ensure no crash.
Reviewed changes
Copilot reviewed 3 out of 3 changed files in this pull request and generated 1 comment.
| File | Description |
|---|---|
| src/Core/src/Handlers/Image/ImageHandler.Windows.cs | Defers background mapping/container creation until the native Image is loaded to avoid COMException during navigation. |
| src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue36694.cs | Adds an Appium UITest that reproduces the navigation + binding update scenario and fails if the app crashes. |
| src/Controls/tests/TestCases.HostApp/Issues/Issue36694.cs | Adds a HostApp issue page that reproduces the crash by changing Image.BackgroundColor via binding while on a different page. |
This comment has been minimized.
This comment has been minimized.
MauiBot
left a comment
There was a problem hiding this comment.
AI Review Summary
@Shalini-Ashokan — new AI review results are available based on this last commit:
ce61391.
🗂️ Review Sessions — click to expand
🚦 Gate — Test Before & After Fix
Gate Result: ✅ PASSED
Platform: WINDOWS · Base: main · Merge base: ee21c935
| Test | Without Fix (expect FAIL) | With Fix (expect PASS) |
|---|---|---|
🖥️ Issue36694 Issue36694 |
✅ FAIL — 597s | ✅ PASS — 458s |
🔴 Without fix — 🖥️ Issue36694: FAIL ✅ · 597s
Error-relevant lines (filtered from the build log):
at UITest.Appium.NUnit.UITestBase.UITestBaseTearDown() in /_/src/TestUtils/src/UITest.NUnit/UITestBase.cs:line 159
at UITest.Appium.NUnit.UITestBase.TestTearDown() in /_/src/TestUtils/src/UITest.NUnit/UITestBase.cs:line 45
🟢 With fix — 🖥️ Issue36694: PASS ✅ · 458s
(no coded error found; showing last 1200 chars)
ched the specified pattern.
NUnit Adapter 4.5.0.0: Test execution started
Running selected tests in D:\a\1\s\artifacts\bin\Controls.TestCases.WinUI.Tests\Debug\net10.0\Controls.TestCases.WinUI.Tests.dll
NUnit3TestExecutor discovered 1 of 1 NUnit test cases using Current Discovery mode, Non-Explicit run
>>>>> 7/23/2026 11:31:39 PM FixtureSetup for Issue36694(Windows)
>>>>> 7/23/2026 11:31:50 PM ChangingImageBackgroundColorAfterNavigationShouldNotThrowCOMException Start
>>>>> 7/23/2026 11:31:53 PM ChangingImageBackgroundColorAfterNavigationShouldNotThrowCOMException Stop
Passed ChangingImageBackgroundColorAfterNavigationShouldNotThrowCOMException [3 s]
NUnit Adapter 4.5.0.0: Test execution complete
[xUnit.net 00:00:00.00] xUnit.net VSTest Adapter v2.8.2+699d445a1a (64-bit .NET 10.0.0)
[xUnit.net 00:00:00.13] Discovering: Controls.TestCases.WinUI.Tests
[xUnit.net 00:00:00.41] Discovered: Controls.TestCases.WinUI.Tests
Results File: D:\a\1\s\CustomAgentLogsTmp\UITests\TestResults\Issue36694.trx
Test Run Successful.
Total tests: 1
Passed: 1
Total time: 27.9490 Seconds
>>> TRX_RESULT_FILE: D:\a\1\s\CustomAgentLogsTmp\UITests\TestResults\Issue36694.trx
📁 Fix files reverted (1 files)
src/Core/src/Handlers/Image/ImageHandler.Windows.cs
📱 UI Tests — Image,ViewBaseTests
Detected UI test categories: Image,ViewBaseTests
🧪 UI Test Execution Results (deep, platform pool)
| Category | Tests | Snapshot diffs |
|---|---|---|
Image |
35/57 (setup failed; 20 marked failed) | — |
ViewBaseTests |
115/115 ✓ | — |
⚠️ Image — fixture setup failed for 20 tests
NUnit reported a OneTimeSetUp/fixture setup failure before test bodies ran; the TRX marked each affected test failed.
OneTimeSetUp: System.InvalidOperationException : The specified element ID is either null or the empty string.
at OpenQA.Selenium.WebElementFactory.GetElementId(Dictionary`2 elementDictionary)
at OpenQA.Selenium.Appium.CachedElementFactory`1.CreateElement(Dictionary`2 elementDictionary)
at OpenQA.Selenium.WebDriver.GetElementsFromResponse(Response response)
at OpenQA.Selenium.WebDriver.FindElements(String mechanism, String value)
at OpenQA.Selenium.Appium.AppiumDriver.FindElements(String selector, String value)
at OpenQA.Selenium.Appium.MobileBy.FindElements(ISearchContext context)
at OpenQA.Selenium.Appium.ByAccessibilityId.FindElements(ISearchContext context)
at OpenQA.Selenium.WebDriver.FindElements(By by)
at OpenQA.Selenium.Appium.AppiumDriver.FindElements(By by)
at UITest.Appium.AppiumQuery.FindElements(AppiumApp appiumApp) in /_/src/TestUtils/src/UITest.Appium/AppiumQuery.cs:line 125
at UITest.Appium.AppiumQueryable.ByAccessibilityId(String name) in /_/src/TestUtils/src/UITest.Appium/AppiumQueryable.cs:line 21
at UITest.Appium.AppiumWindowsApp.FindElement(String id) in /_/src/TestUtils/src/UITest.Appium/AppiumWindowsApp.cs:line 44
at UITest.Appium.HelperExtensions.<>c__DisplayClass63_0.<WaitForNoElement>g__result|0() in /_/src/TestUtils/src/UITest.Appium/HelperExtensions.cs:line 997
at UITest.Appium.HelperExtensions.Wait(Func`1 query, Func`2 satisfactory, String timeoutMessage, Nullable`1 timeout, Nullable`1 retryFreque
...
📎 Download drop-deep-uitests artifact (TRX + snapshot diffs)
🔗 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/Core/src/Handlers/Image/ImageHandler.Windows.cs |
#35923 |
📋 Pre-Flight — Context & Validation
Issue: #36694 - [Windows] Setting BackgroundColor on Image causes InteropServices.COMException
PR: #36747 - [Windows] Fix COMException when changing Image BackgroundColor via binding after navigation
Platforms Affected: Windows
Files Changed: 1 implementation, 2 test
Key Findings
- Issue #36694 reports a Windows-only
System.Runtime.InteropServices.COMExceptionwhen anImagestarts with nullBackgroundColorand later receives a background via binding. - PR #36747 changes
src/Core/src/Handlers/Image/ImageHandler.Windows.csso background/container updates are deferred until the WinUIImageis loaded, and adds an Appium repro underIssue36694. - Public PR discussion includes a Copilot inline comment noting that
MapBackground(IImageHandler, IImage)now silently skips non-ImageHandlerimplementations. - Gate result supplied by caller: PASS - tests fail without fix and pass with PR fix. Gate was not re-run.
Code Review Summary
Verdict: NEEDS_CHANGES
Confidence: low
Errors: 1 | Warnings: 1 | Suggestions: 0
Key code review findings:
- Error:
src/Core/src/Handlers/Image/ImageHandler.Windows.cs:145- publicMapBackgroundnow no-ops for custom/nonstandardIImageHandlerimplementations instead of preserving the prior synchronous background mapping behavior. - Warning:
src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue36694.cs:22- UI test verifies no crash but not that the deferred red background is actually applied after navigation back.
Fix Candidates
| # | Source | Approach | Test Result | Files Changed | Notes |
|---|---|---|---|---|---|
| PR | PR #36747 | Defer MapBackground container/background update until ImageHandler.PlatformView.Loaded, then rerun container and background mappings in OnImageLoaded. |
PASS (Gate) | src/Core/src/Handlers/Image/ImageHandler.Windows.cs, 2 UI test files |
Original PR; code review found custom-handler regression. |
🔬 Code Review — Deep Analysis
Code Review — PR #36747
Independent Assessment
What this changes: Windows ImageHandler.MapBackground now defers background/container updates until the WinUI Image is loaded, then reapplies background from OnImageLoaded. It also adds an Appium navigation repro.
Inferred motivation: Avoid WinUI COMException when background changes while the previous page's image is unloaded.
Reconciliation with PR Narrative
Author claims: Fixes a Windows crash caused by creating the image wrapper/container while unloaded after navigation.
Agreement/disagreement: The root cause and default ImageHandler approach match the code. However, the implementation changes public mapper behavior for non-ImageHandler IImageHandler implementations.
Prior Review Reconciliation
| Prior Error Finding | Source | Status | Evidence |
|---|---|---|---|
| No prior Error findings found. | - | - | Prior Copilot inline comment raised the same custom-handler concern but was not marked Error; it remains valid in current code. |
Blast Radius Assessment
- Runs for all instances: Yes - every Windows
Image.Backgroundmapper update. - Startup impact: No direct startup path, but applies during handler/property mapping.
- Static/shared state: No.
CI Status
- Required-check result: Tool-unavailable via
gh pr checks --requiredbecauseghis unauthenticated. - Classification: Public check-runs show
maui-pr/Build Analysis failing; visible failures appear unrelated infra/JDK plus unrelated Dispatcher unit failure, but required-check status could not be authenticated. - Action taken: Invoked
azdo-build-investigator; capped confidence low.
Findings
Error — Public mapper now silently no-ops for custom IImageHandler
src/Core/src/Handlers/Image/ImageHandler.Windows.cs:145
MapBackground is public and accepts IImageHandler, but the new implementation only performs the background update inside if (handler is ImageHandler imghandler). Any custom/nonstandard IImageHandler reusing this mapper now silently skips both UpdateValue(nameof(IViewHandler.ContainerView)) and UpdateBackground(image), where it previously worked. The default handler can still use the deferred Loaded path, but non-ImageHandler implementations should preserve the previous synchronous mapping behavior.
Warning — UI test only verifies no crash, not that deferred background is applied
src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue36694.cs:22
Waiting for ResultLabel after navigating back would pass even if the fix avoided the COMException by never applying the red background. The test should assert visible state after return, e.g. expose a result that confirms TestImage.BackgroundColor == Colors.Red.
Failure-Mode Probing
- Custom handler reuses mapper: current code returns without applying background; regression confirmed from control flow.
- Handler disconnect before
Loaded:DisconnectHandlerunsubscribes andOnImageLoadedchecksIsConnected(), so this path is guarded. - Multiple background changes while unloaded:
Loaded -=/+=avoids duplicate subscriptions and re-reads current background on load.
Verdict: NEEDS_CHANGES
Confidence: low
Summary: The default Windows crash fix is plausible, but the public mapper regression for custom IImageHandler implementations should be fixed before merge. Confidence is capped by unauthenticated required-check status and red public CI.
🛠️ Fix — Analysis & Comparison
Fix Candidates
| # | Source | Approach | Test Result | Files Changed | Notes |
|---|---|---|---|---|---|
| 1 | try-fix-1 | Move unloaded-view deferral into ImageHandler.SetupContainer, keep public MapBackground(IImageHandler, IImage) universal, and rerun background mapping from OnImageLoaded. |
PASS | 1 file | Preserves custom/non-ImageHandler mapper behavior and protects any SetupContainer trigger, not just Background. |
| PR | PR #36747 | Gate MapBackground itself on ImageHandler/IsLoaded, defer via Loaded, then rerun background mapping from OnImageLoaded. |
PASS (Gate) | 1 implementation file + 2 test files | Original PR; code review found public mapper regression for custom IImageHandler implementations. |
try-fix-1 Details
Approach: Guard in SetupContainer + universal MapBackground.
Why different from PR: The PR places the unloaded-view check inside the public static mapper and only applies background for the concrete ImageHandler. Candidate #1 keeps the mapper behavior equivalent to the pre-PR implementation for all IImageHandler implementations and moves WinUI parent-panel safety to the instance container setup path where the COMException is triggered.
Test Results: PASS
BuildAndRunHostApp.ps1 -Platform windows -TestFilter "FullyQualifiedName~Issue36694"
- Test Run Successful.
- Total tests: 1
- Passed: 1
- Result: SUCCESS
Self-review: 0 findings (reviewer-findings.json is []).
Diff:
diff --git a/src/Core/src/Handlers/Image/ImageHandler.Windows.cs b/src/Core/src/Handlers/Image/ImageHandler.Windows.cs
index c0f5e4b05e..6d591b28a0 100644
--- a/src/Core/src/Handlers/Image/ImageHandler.Windows.cs
+++ b/src/Core/src/Handlers/Image/ImageHandler.Windows.cs
@@ -42,6 +42,17 @@ namespace Microsoft.Maui.Handlers
/// <inheritdoc/>
protected override void SetupContainer()
{
+ var platformView = PlatformView;
+ if (platformView is not null && !platformView.IsLoaded)
+ {
+ // Defer container setup until the view is in the active visual tree.
+ // Manipulating the parent panel while the page is not loaded causes a
+ // COMException. See https://github.com/dotnet/maui/issues/36694
+ platformView.Loaded -= OnImageLoaded;
+ platformView.Loaded += OnImageLoaded;
+ return;
+ }
+
base.SetupContainer();
// VerticalAlignment only works when the child's Height is Auto
@@ -137,6 +148,11 @@ namespace Microsoft.Maui.Handlers
/// <param name="image">The associated <see cref="Image"/> instance.</param>
public static void MapBackground(IImageHandler handler, IImage image)
{
+ if (handler.PlatformView is null)
+ {
+ return;
+ }
+
handler.UpdateValue(nameof(IViewHandler.ContainerView));
handler.ToPlatform().UpdateBackground(image);
}
@@ -187,6 +203,7 @@ namespace Microsoft.Maui.Handlers
}
UpdateValue(nameof(IViewHandler.ContainerView));
+ UpdateValue(nameof(IImage.Background));
}
}
Failure Analysis: N/A - candidate passed the targeted Windows UI test.
Cross-Pollination
| Model | Round | New Ideas? | Details |
|---|---|---|---|
| claude-opus-4.6 | 1 | Yes | Candidate #1: guard SetupContainer, preserve universal MapBackground. |
| Remaining models | 1 | Not run | Stop criterion met: candidate passed all targeted tests and is demonstrably better than the PR fix because it fixes the code-review error while preserving the PR's crash behavior. |
Exhausted: No
Selected Fix: Candidate #1 - it passed the same Windows UI regression test and removes the PR fix's public mapper regression for custom/non-ImageHandler implementations while keeping the deferred background/container behavior.
📝 Recommended PR Title & Description
Assessment: ✏️ Recommend updating — the current description describes the raw PR's MapBackground-level IsLoaded gate, but the winning fix moves deferral into ImageHandler.SetupContainer() to preserve generic IImageHandler mapper behavior.
Recommended title
[Windows] Image: Defer background container setup until loaded
Recommended description
### Issue Details
Setting BackgroundColor on an Image control through a ViewModel binding crashes the app with a COMException on Windows. The crash only happens when the color starts as null and is changed while the user has navigated to a different page. The Image on the previous page is still bound to the ViewModel, so the property change triggers handler code on an unloaded view.
### Root Cause
When the BackgroundColor changes from null to a color, the ImageHandler needs to create a WrapperView container around the native Image. This involves removing the Image from its parent panel and re-adding it inside the new container. On Windows, when the page is navigated away, the Image is unloaded from the visual tree — WinUI throws a COMException because it forbids adding disconnected elements to new panels.
### Description of Change
Defers Windows Image container setup until the native Image is loaded before manipulating its parent panel. The unloaded-view check is scoped to `ImageHandler.SetupContainer()`, where the unsafe container creation happens, rather than making the public `MapBackground(IImageHandler, IImage)` mapper conditional on the concrete `ImageHandler` type.
When the Image loads again, `OnImageLoaded` reruns the container and background mappings so the deferred BackgroundColor is applied safely after navigation returns to the page.
### Key Technical Details
- `ImageHandler.SetupContainer()` now subscribes to `Loaded` and returns when the WinUI Image is not in the active visual tree.
- `ImageHandler.MapBackground(IImageHandler, IImage)` remains a generic mapper for all `IImageHandler` implementations.
- `OnImageLoaded` unsubscribes from `Loaded`, verifies the handler is still connected, then updates `ContainerView` and `Background`.
- Added an Appium regression test for the navigation/binding scenario from #36694.
### What NOT to Do
- Don't gate `MapBackground(IImageHandler, IImage)` only on concrete `ImageHandler` — custom/non-derived `IImageHandler` implementations can reuse the mapper and should keep receiving background updates.
- Don't only avoid the COMException; the deferred red BackgroundColor must still be applied when the Image loads again.
Validated the behavior in the following platforms
- [x] Android
- [x] Windows
- [x] iOS
- [x] Mac
### Issues Fixed
Fixes #36694
### Output ScreenShot
|Before|After|
|--|--|
| <video src="https://github.com/user-attachments/assets/f0bf2ce9-48ae-45e5-8a50-635a34436184" >| <video src="https://github.com/user-attachments/assets/f2ae02ca-fec7-4d2f-ad96-d9f066ad9b10">|
🏁 Report — Final Recommendation
Comparative Report — PR #36747
Candidates compared
| Rank | Candidate | Regression test status | Review status | Assessment |
|---|---|---|---|---|
| 1 | pr-plus-reviewer |
Implementation matches passing try-fix-1; raw PR gate also passed |
Fixes expert review major finding and addresses test coverage warning | Winner. Keeps the intended Windows COMException fix, preserves MapBackground(IImageHandler, IImage) behavior for custom handlers, and improves regression coverage. |
| 2 | try-fix-1 |
PASS | Self-review found 0 findings | Strong implementation candidate. It moves the deferral to SetupContainer() and preserves universal MapBackground, but it does not include the expert review's test-coverage improvement. |
| 3 | pr |
PASS (caller-provided gate) | Expert review found 1 major issue and 1 moderate issue | Correctly targets the crash, but regresses custom/non-derived IImageHandler mapper reuse by making MapBackground no-op outside concrete ImageHandler. |
No candidate in the provided STEP 5a artifacts failed regression tests. If any later candidate is discovered with a failed regression result, it must rank below all passing candidates.
Winning candidate
pr-plus-reviewer wins because it combines the verified crash-fix behavior with the expert review corrections:
- The unsafe operation is container setup while the WinUI image is unloaded, so the loaded-state deferral belongs in
ImageHandler.SetupContainer(). MapBackground(IImageHandler, IImage)remains a generic public mapper and continues to work for custom/non-derivedIImageHandlerimplementations.OnImageLoadedreruns both container and background mappings so deferred background changes are applied when the page returns.- The test should assert the deferred background result, not only that the app avoids a COMException.
Recommendation
Use pr-plus-reviewer as the final fix direction. If minimizing changes is required, try-fix-1 is the best implementation-only fallback and is still materially better than the raw PR fix.
🧭 Next Steps — review latest findings
No alternative fix was selected for this run. Review the session findings and CI results before merging.
MauiBot
left a comment
There was a problem hiding this comment.
Expert Review — 2 findings
See inline comments for details.
| App.WaitForElement("ChangeColorButton"); | ||
| App.Tap("ChangeColorButton"); | ||
| App.Tap("GoBackButton"); | ||
| App.WaitForElement("ResultLabel"); | ||
| } |
|
/azp run maui-pr-uitests , maui-pr-devicetests |
|
Azure Pipelines: Successfully started running 2 pipeline(s). |
This comment has been minimized.
This comment has been minimized.
|
Warning 🔍 Automated review could not completeA stage of the reviewer pipeline could not finish, so no review summary was produced for this run — most often the review stage itself hanging, or the run being canceled by its overall timeout. This is almost always a transient infrastructure issue on the CI agent, not a problem with your PR. (Note: a test-verification gate timeout no longer lands here — it now posts a normal AI Summary whose Gate section explains the timeout.) Please re-comment 🔍 Automated message from the .NET MAUI Copilot reviewer pipeline · build log |
…nding after navigation (#36747) <!-- 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. !!!!!!! --> ### Issue Details Setting BackgroundColor on an Image control through a ViewModel binding crashes the app with a COMException on Windows. The crash only happens when the color starts as null and is changed while the user has navigated to a different page. The Image on the previous page is still bound to the ViewModel, so the property change triggers handler code on an unloaded view. ### Root Cause When the BackgroundColor changes from null to a color, the ImageHandler needs to create a WrapperView container around the native Image. This involves removing the Image from its parent panel and re-adding it inside the new container. On Windows, when the page is navigated away, the Image is unloaded from the visual tree — WinUI throws a COMException because it forbids adding disconnected elements to new panels. ### Description of Change Added an IsLoaded check in MapBackground before attempting container creation. If the Image is not currently in the visual tree, the work is deferred by subscribing to the Loaded event. When the user navigates back and the page loads again, OnImageLoaded fires and safely creates the container and applies the background Validated the behavior in the following platforms - [x] Android - [x] Windows - [x] iOS - [x] Mac ### Issues Fixed Fixes #36694 ### Output ScreenShot |Before|After| |--|--| | <video src="https://github.com/user-attachments/assets/f0bf2ce9-48ae-45e5-8a50-635a34436184" >| <video src="https://github.com/user-attachments/assets/f2ae02ca-fec7-4d2f-ad96-d9f066ad9b10">|
…nding after navigation (#36747) <!-- 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. !!!!!!! --> ### Issue Details Setting BackgroundColor on an Image control through a ViewModel binding crashes the app with a COMException on Windows. The crash only happens when the color starts as null and is changed while the user has navigated to a different page. The Image on the previous page is still bound to the ViewModel, so the property change triggers handler code on an unloaded view. ### Root Cause When the BackgroundColor changes from null to a color, the ImageHandler needs to create a WrapperView container around the native Image. This involves removing the Image from its parent panel and re-adding it inside the new container. On Windows, when the page is navigated away, the Image is unloaded from the visual tree — WinUI throws a COMException because it forbids adding disconnected elements to new panels. ### Description of Change Added an IsLoaded check in MapBackground before attempting container creation. If the Image is not currently in the visual tree, the work is deferred by subscribing to the Loaded event. When the user navigates back and the page loads again, OnImageLoaded fires and safely creates the container and applies the background Validated the behavior in the following platforms - [x] Android - [x] Windows - [x] iOS - [x] Mac ### Issues Fixed Fixes #36694 ### Output ScreenShot |Before|After| |--|--| | <video src="https://github.com/user-attachments/assets/f0bf2ce9-48ae-45e5-8a50-635a34436184" >| <video src="https://github.com/user-attachments/assets/f2ae02ca-fec7-4d2f-ad96-d9f066ad9b10">|
…nding after navigation (#36747) <!-- 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. !!!!!!! --> ### Issue Details Setting BackgroundColor on an Image control through a ViewModel binding crashes the app with a COMException on Windows. The crash only happens when the color starts as null and is changed while the user has navigated to a different page. The Image on the previous page is still bound to the ViewModel, so the property change triggers handler code on an unloaded view. ### Root Cause When the BackgroundColor changes from null to a color, the ImageHandler needs to create a WrapperView container around the native Image. This involves removing the Image from its parent panel and re-adding it inside the new container. On Windows, when the page is navigated away, the Image is unloaded from the visual tree — WinUI throws a COMException because it forbids adding disconnected elements to new panels. ### Description of Change Added an IsLoaded check in MapBackground before attempting container creation. If the Image is not currently in the visual tree, the work is deferred by subscribing to the Loaded event. When the user navigates back and the page loads again, OnImageLoaded fires and safely creates the container and applies the background Validated the behavior in the following platforms - [x] Android - [x] Windows - [x] iOS - [x] Mac ### Issues Fixed Fixes #36694 ### Output ScreenShot |Before|After| |--|--| | <video src="https://github.com/user-attachments/assets/f0bf2ce9-48ae-45e5-8a50-635a34436184" >| <video src="https://github.com/user-attachments/assets/f2ae02ca-fec7-4d2f-ad96-d9f066ad9b10">|
…nding after navigation (#36747) <!-- 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. !!!!!!! --> ### Issue Details Setting BackgroundColor on an Image control through a ViewModel binding crashes the app with a COMException on Windows. The crash only happens when the color starts as null and is changed while the user has navigated to a different page. The Image on the previous page is still bound to the ViewModel, so the property change triggers handler code on an unloaded view. ### Root Cause When the BackgroundColor changes from null to a color, the ImageHandler needs to create a WrapperView container around the native Image. This involves removing the Image from its parent panel and re-adding it inside the new container. On Windows, when the page is navigated away, the Image is unloaded from the visual tree — WinUI throws a COMException because it forbids adding disconnected elements to new panels. ### Description of Change Added an IsLoaded check in MapBackground before attempting container creation. If the Image is not currently in the visual tree, the work is deferred by subscribing to the Loaded event. When the user navigates back and the page loads again, OnImageLoaded fires and safely creates the container and applies the background Validated the behavior in the following platforms - [x] Android - [x] Windows - [x] iOS - [x] Mac ### Issues Fixed Fixes #36694 ### Output ScreenShot |Before|After| |--|--| | <video src="https://github.com/user-attachments/assets/f0bf2ce9-48ae-45e5-8a50-635a34436184" >| <video src="https://github.com/user-attachments/assets/f2ae02ca-fec7-4d2f-ad96-d9f066ad9b10">|
Note
Are you waiting for the changes in this PR to be merged?
It would be very helpful if you could test the resulting artifacts from this PR and let us know in a comment if this change resolves your issue. Thank you!
Issue Details
Setting BackgroundColor on an Image control through a ViewModel binding crashes the app with a COMException on Windows. The crash only happens when the color starts as null and is changed while the user has navigated to a different page. The Image on the previous page is still bound to the ViewModel, so the property change triggers handler code on an unloaded view.
Root Cause
When the BackgroundColor changes from null to a color, the ImageHandler needs to create a WrapperView container around the native Image. This involves removing the Image from its parent panel and re-adding it inside the new container. On Windows, when the page is navigated away, the Image is unloaded from the visual tree — WinUI throws a COMException because it forbids adding disconnected elements to new panels.
Description of Change
Added an IsLoaded check in MapBackground before attempting container creation. If the Image is not currently in the visual tree, the work is deferred by subscribing to the Loaded event. When the user navigates back and the page loads again, OnImageLoaded fires and safely creates the container and applies the background
Validated the behavior in the following platforms
Issues Fixed
Fixes #36694
Output ScreenShot
36694-BeforeFix.mov
36694-AfterFix.mov