Skip to content

feat(WebView2): add Extensions for providing attached properties that can be used to avoid code behind in Mvux using Apps - #21474

Closed
DevTKSS wants to merge 13 commits into
unoplatform:masterfrom
DevTKSS:feat-WebView2-add-and-improve-controls-API
Closed

DevTKSS wants to merge 13 commits into
unoplatform:masterfrom
DevTKSS:feat-WebView2-add-and-improve-controls-API

Conversation

@DevTKSS

@DevTKSS DevTKSS commented Sep 13, 2025 •

Copy link
Copy Markdown
Contributor

GitHub Issue: closes #21473

PR Type:

  • ✨ Feature

What is the current behavior? 🤔

  • There is no Property existing on the WebView2 that can be used to check if its currently Navigating, e.g. for Binding a ProgressRing to it like its possible in a Chrome Browser, without having to register own Event Handlers for the Navigating Events
    We need to manually subscribe to the NavigationStarted and NavigationCompleted Eventhandlers and need to add an DependencyProperty Registration to get a Binding supporting and automatically update-able in the shown UI like this
public sealed partial class MainPage : Page
{
   private static DependencyProperty WebViewIsNavigatingProperty { get; } =
       DependencyProperty.Register(
           nameof(WebViewIsNavigating),
           typeof(bool),
           typeof(MainPage),
           new PropertyMetadata(default(bool)));

    internal bool WebViewIsNavigating 
    {
        get => (bool)GetValue(WebViewIsNavigatingProperty);
        private set => SetValue(WebViewIsNavigatingProperty,value); 
    }

   public MainPage()
   {
       this.InitializeComponent();

       MyWebView2.NavigationStarting += (s, e) =>
       {
           WebViewIsNavigating = true;
       };
       MyWebView2.NavigationCompleted += (s, e) =>
       {
           WebViewIsNavigating = false;
       };
       MyWebView2.CoreWebView2.DocumentTitleChanged += (s, e) =>
       {
MyWebView2.CoreWebView2.DocumentTitle);
           MyNavigationBar.Content = MyWebView2.CoreWebView2.DocumentTitle;
       };
    ```

and bound a TextBlock Run to the value of this same as a ProgressRing:

```xml
<TextBlock x:Name="NavigationStatusBlock">
    <Run Text="WebView2 Navigation status: " />
    <Run Text="{x:Bind Path=WebViewIsNavigating,Mode=OneWay}" />
</TextBlock>
<ProgressRing IsActive="{x:Bind Path=WebViewIsNavigating, Mode=OneWay}"
Grid.Column="5"
Visibility="{x:Bind Path=WebViewIsNavigating, Mode=OneWay, Converter={StaticResource FalseToCollapsedConverter}}" />

find more screenshots of the app I did on my recent post on Discord

  • In Mvux based Uno Apps, we are normally avoiding or at least trying to keep our Code Behind as small as possible, but while the DocumentTitle Property the CoreWebView2 is a DependencyProperty, the WebView2.CoreWebView2 is not, so we can not reach this through Xaml and our only Chance to get the updated DocumentTitle is by manually subscribing to the EventHandler in the Code behind
  • Alternativ to DP's we would be required to add each of them through setters of the Property normally xaml bound Property.

What is the new behavior? 🚀

  • Adds DocumentTitle and IsNavigating as Attach-able Properties accepting to be bound to an WebView2 control, mirroring functionality from the "old" WebView, but without changing the actual API of WebView2.

  • If attached, the Extensions DP will be subscribing for us to the following Events and allowing us to Bind to the property value through Xaml without needing Code behind 👍 :

    • DocumentTitleChanged of the WebView2.CoreWebView2
    • NavigationStarted + NavigationCompleted and provides the Boolean property IsNavigating
  • xml Documentation:

    • Improves documentation for existing public members by fixing of spellcheck lintings in the existing definition of WebView2 and native representations.
    • Adds Documentation to those which doesn't have documentation until now

PR Checklist ✅

Please check if your PR fulfills the following requirements:

Other information ℹ️

I did not add Tests because:

  • Opening the Uno.UI Solution (without filters) does give me the issued behaviour mentioned on the discord Contributing Channel
    image
  • The Docs about creating UITests are not even followable for creating UI Tests for own projects and only existing for the contributing section, which are not telling enough to understand what the SamplesApp does, at least for me.

Copilot AI review requested due to automatic review settings September 13, 2025 16:45
@github-actions github-actions Bot added platform/wasm 🌐 Categorizes an issue or PR as relevant to the WebAssembly platform platform/android 🤖 Categorizes an issue or PR as relevant to the Android platform platform/ios 🍎 Categorizes an issue or PR as relevant to the iOS platform labels Sep 13, 2025

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull Request Overview

This PR enhances the WebView2 control by adding missing API features and fixing event handling issues. It introduces the DocumentTitle and IsNavigating properties to enable data binding scenarios and improves the DocumentTitleChanged event to properly pass the title value instead of null.

  • Adds DocumentTitle and IsNavigating dependency properties for better data binding support
  • Fixes DocumentTitleChanged event to pass actual title value instead of hardcoded null
  • Improves XML documentation across the WebView2 API surface

Reviewed Changes

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

Show a summary per file
File Description
WebView2.cs Adds event handler registration and navigation state tracking logic
WebView2.Properties.cs Defines new dependency properties and events with proper documentation
UnoWKWebView.iOSmacOS.cs Updates document title change handling to pass actual title value
NativeWebView.wasm.cs Updates document title change handling to pass actual title value
HtmlWebViewElement.wasm.cs Updates document title change handling to pass actual title value
NativeWebViewWrapper.Android.cs Updates document title change handling and fixes comment typo
CoreWebView2.cs Updates event raising method signature and adds comprehensive documentation
CoreWebView2.Properties.cs Fixes grammar in XML documentation comments

@DevTKSS

DevTKSS commented Sep 13, 2025

Copy link
Copy Markdown
Contributor Author

If the changes are okay, I could then add the added DependencyProperty to the Uno specifics Docs, but would eitherway plan to create a CommunityTutorial about this for what I did on my app.

@unodevops

Copy link
Copy Markdown
Contributor

@unodevops

Copy link
Copy Markdown
Contributor

@unodevops

Copy link
Copy Markdown
Contributor

@unodevops

Copy link
Copy Markdown
Contributor

@unodevops

Copy link
Copy Markdown
Contributor

⚠️⚠️ The build 176048 has failed on Uno.UI - CI.

@DevTKSS

DevTKSS commented Sep 15, 2025

Copy link
Copy Markdown
Contributor Author

Hey @Xiaoy312 do you or someone else of the team maybe could check this out? Maybe we could add those things right into the WebView2? For the DocumentTitle this is already existing on the normal "old" WebView control (and many other things too👀 we dont have on the new one like the HttpMessage Navigation action) but not on the 2 one that we are recommended to use.

So maybe we could get this also added on the 2? 🥹

/// <summary>
/// Occurs when the title for the current top-level document changes.
/// </summary>
public event TypedEventHandler<WebView2, object> DocumentTitleChanged;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Since this a new property, we'll now need a runtime test that provides a way to validate that this property is properly populated.

You can create one in

.

If you've never created runtime tests, make sure to review our documentation on the topic.

@DevTKSS DevTKSS Sep 18, 2025 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Okay, but of you readed the OP above, you might have seen that one of the test projects (the UI test project with Wasm ending) does state "Not Compartible" and VS2022 does not succeed to even load that project which normally comes before writing, building or running a test.
I pointed that issue on the contribution channel on discord and Martin did even comment on that, that its a good finding, so I would guess its valid...

Could you eventually check on this and let me know how to proceed on that?

Another point: The wasm sampleapp ci/cd-build here does also not succeed here even on GH while I did so far not edit it at all.
Is that normal? If it doesn't succeed before I add a test, i would expect it to fail afterwards too 🤔

One other question to the DocumentTitleChanged Typed Event handler:
I do and did see that its argument type is object which is why I set the Copilot review comments about that to solved (fit its instructions to the implemented view API 's that we do not change those signatures?)
but there was no information about what they meaning us to find in there. I would assume from the Naming, that we expect it to return us the new Document title, but I am not completely sure if it is.
Do we have any way to check this?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Okay, but of you readed the OP above, you might have seen that one of the test projects (the UI test project with Wasm ending) does state "Not Compartible" and VS2022 does not succeed to even load that project which normally comes before writing, building or running a test.
I pointed that issue on the contribution channel on discord and Martin did even comment on that, that its a good finding, so I would guess its valid...

This is unrelated to the change you're making, please don't mix up the threads :)

Another point: The wasm sampleapp ci/cd-build here does also not succeed here even on GH while I did so far not edit it at all.

No problem about this, make sure to make the runtime test first, the rest will fall into place.

One other question to the DocumentTitleChanged Typed Event handler:
I do and did see that its argument type is object which is why I set the Copilot review comments about that to solved (fit its instructions to the implemented view API 's that we do not change those signatures?)
but there was no information about what they meaning us to find in there. I would assume from the Naming, that we expect it to return us the new Document title, but I am not completely sure if it is.
Do we have any way to check this?

Don't mind the copilot reports, it cannot know about the right APIs.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@jeromelaban Dropped the WebView2 Type API changes, only xml docs updates (see updated OP) there

Do you want me to add the Tests to the Attached Property Definition then still in the Given_WebView2 Test file or rather create another seperate test file for this in this Project?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@jeromelaban I wasn't able to find an Attached Property Extension test so far, which I could take as sample/template for this and Copilot suggests all the time to create another and another Helper - Host Object while I would prefer to validate the test mainly using xaml, as this should be the target usage and because of I have no idea how to access a DP for a Control via codebehind 😅
Do you maybe have a lookup you know of and I could check out for this?

@unodevops

Copy link
Copy Markdown
Contributor

@unodevops

Copy link
Copy Markdown
Contributor

⚠️⚠️ The build 177065 has failed on Uno.UI - CI.

@DevTKSS

DevTKSS commented Oct 23, 2025

Copy link
Copy Markdown
Contributor Author

@MartinZikmund could you enqueue this for review ready list?

Would not know how I could make it better with my limited knowledge in attached properties 😅, but maybe the team has after finishing the conf😁

Thanks! 👍

Copilot AI review requested due to automatic review settings November 13, 2025 20:45

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot encountered an error and was unable to review this pull request. You can try again by re-requesting a review.

@unodevops

Copy link
Copy Markdown
Contributor

@unodevops

Copy link
Copy Markdown
Contributor

⚠️⚠️ The build 182847 has failed on Uno.UI - CI.

@github-actions github-actions Bot removed platform/wasm 🌐 Categorizes an issue or PR as relevant to the WebAssembly platform platform/ios 🍎 Categorizes an issue or PR as relevant to the iOS platform labels Nov 30, 2025
@unodevops

Copy link
Copy Markdown
Contributor

@DevTKSS DevTKSS changed the title Feat(WebView2): add, fix and improve api feat(WebView2): add Extensions for providing attached properties that can be used to avoid code behind in Mvux using Apps Nov 30, 2025
@unodevops

Copy link
Copy Markdown
Contributor

⚠️⚠️ The build 185727 has failed on Uno.UI - CI.

@unodevops

Copy link
Copy Markdown
Contributor

@unodevops

Copy link
Copy Markdown
Contributor

⚠️⚠️ The build 187688 has failed on Uno.UI - docs.

@DevTKSS
DevTKSS force-pushed the feat-WebView2-add-and-improve-controls-API branch from 70998a5 to 8541719 Compare December 12, 2025 13:43
…lers to improve clarity

- Referencing code names with xml tags provides build in lookup capability
- adds notes regarding the DocumentTitleChanged event arguments which are expected to always be null
- adds Remarks to the target usage of the Event Handler Events
@unodevops

Copy link
Copy Markdown
Contributor

⚠️⚠️ The build 187695 has failed on Uno.UI - docs.

@DevTKSS
DevTKSS force-pushed the feat-WebView2-add-and-improve-controls-API branch from 8541719 to a2acdb1 Compare December 12, 2025 14:22
@unodevops

Copy link
Copy Markdown
Contributor

@unodevops

Copy link
Copy Markdown
Contributor

@unodevops

Copy link
Copy Markdown
Contributor

@unodevops

Copy link
Copy Markdown
Contributor

@unodevops

Copy link
Copy Markdown
Contributor

⚠️⚠️ The build 187719 has failed on Uno.UI - CI.

@DevTKSS

DevTKSS commented Dec 13, 2025

Copy link
Copy Markdown
Contributor Author

Using the suggested Event Subscription from IsNavigating and Binding in my own App with xaml:

<ProgressRing IsActive="{Binding ElementName=MyWebView2, Path=(wv2:WebView2Extensions.IsNavigating), Mode=OneWay}"
              Grid.Column="5" />
<TextBlock x:Name="NavigationStatusBlock">
                    <Run Text="WebView2 Navigation status: " />
                 <Run Text="{Binding ElementName=MyWebView2, Path=(wv2:WebView2Extensions.IsNavigating), Mode=OneWay}" />
                </TextBlock>

Does not even enter the OnIsNavigationChanged DP Callback Handler, so I assume there is somewhere still a bug to fix.
Waiting for Answer if this can be done with Runtime Tests or if this instead needs UI / Unit Tests 🤔
The UI does never update to state IsNavigating would be true and I found so far no Test example for Attached Dependency Properties + validating its usage in xaml markup🤷

@DevTKSS
DevTKSS requested a review from Xiaoy312 December 13, 2025 13:17
@DevTKSS

DevTKSS commented Feb 11, 2026

Copy link
Copy Markdown
Contributor Author

@Jen-Uno WebView2 is available for all Targets if I read the docs wrong, but seems like your actions-bot did remove some target tags?
And would be cool if anyone could take a look on this PR, my experience is not enough to make those decisions and I found no extensions tests for UI elements like this here. Docs are not really helpful for this and agents are seeming to create "host" things while I would guess Uno has already such thing but I don't know how to do this correctly 😬👀

@Jen-Uno

Jen-Uno commented Feb 11, 2026

Copy link
Copy Markdown
Contributor

@MartinZikmund could you take a look?

Copilot AI review requested due to automatic review settings March 11, 2026 11:49

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

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


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

Comment on lines +50 to +100
private static void OnIsNavigatingChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
if (sender is not WebView2 control)
{
throw new InvalidOperationException("The attached property 'IsNavigating' can only be applied to a WebView2 control.");
}

// Always remove previous event handlers to prevent duplicate subscriptions
control.NavigationStarting -= OnNavigationStarting;
control.NavigationCompleted -= OnNavigationCompleted;
control.Unloaded -= OnControlUnloaded;

// Only subscribe if the new value is true
if (e.NewValue is bool isEnabled && isEnabled)
{
control.NavigationStarting += OnNavigationStarting;
control.NavigationCompleted += OnNavigationCompleted;
control.Unloaded += OnControlUnloaded;
}
}

/// <summary>
/// Handles the <see cref="WebView2.Unloaded"/> event for the attached <see cref="WebView2"/> control and removes any event subscriptions:
/// <list type="bullet">
/// <item><see cref="WebView2.NavigationStarting"/></item>
/// <item><see cref="WebView2.NavigationCompleted"/></item>
/// <item><see cref="CoreWebView2.DocumentTitleChanged"/></item>
/// </list>
/// </summary>
/// <param name="sender">The <see cref="WebView2"/> control that was unloaded.</param>
/// <param name="e"> The <see cref="RoutedEventArgs"/> event data.</param>
private static void OnControlUnloaded(object sender, RoutedEventArgs e)
{
if (sender is WebView2 control)
{
control.NavigationStarting -= OnNavigationStarting;
control.NavigationCompleted -= OnNavigationCompleted;
control.Unloaded -= OnControlUnloaded;

if (control.CoreWebView2 is not null)
{
control.CoreWebView2.DocumentTitleChanged -= OnCoreDocumentTitleChanged;
}
}
}

private static void OnNavigationStarting(WebView2 sender, CoreWebView2NavigationStartingEventArgs args)
=> SetIsNavigating(sender, true);

private static void OnNavigationCompleted(WebView2 sender, CoreWebView2NavigationCompletedEventArgs args)
=> SetIsNavigating(sender, false);

Copilot AI Mar 11, 2026

Copy link

Choose a reason for hiding this comment

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

IsNavigatingProperty is being used both as the switch to subscribe/unsubscribe and as the state updated by navigation events (OnNavigationStarting/OnNavigationCompleted call SetIsNavigating). This causes the callback to remove handlers on navigation completion (when it sets the value to false), so subsequent navigations won't be tracked, and it also churns subscriptions on every state update. Consider splitting this into two attached properties (e.g., TrackIsNavigating/IsNavigating) or using a separate internal attached property to hold the tracking flag while IsNavigating is updated without triggering subscription logic.

Copilot uses AI. Check for mistakes.
Comment on lines +109 to +170
public static DependencyProperty DocumentTitleProperty { [DynamicDependency(nameof(GetDocumentTitle))] get; } = DependencyProperty.RegisterAttached(
"DocumentTitle",
typeof(string),
typeof(WebView2Extensions),
new PropertyMetadata(string.Empty, OnDocumentTitleChanged));

/// <summary>
/// Gets the value of the <see cref="DocumentTitleProperty">DocumentTitle Attached Property</see> for the specified <see cref="DependencyObject"/>.
/// </summary>
/// <param name="obj">The object from which to get the property value.</param>
/// <returns>The document title of the WebView2 control.</returns>
[DynamicDependency(nameof(SetDocumentTitle))]
public static string GetDocumentTitle(DependencyObject obj) => (string)(obj.GetValue(DocumentTitleProperty) ?? string.Empty);

/// <summary>
/// Sets the value of the <see cref="DocumentTitleProperty">DocumentTitle Attached Property</see> for the specified <see cref="DependencyObject"/>.<br/>
/// When set, enables automatic tracking of document title changes on the <see cref="WebView2"/> control.
/// </summary>
/// <param name="obj">The object on which to set the property value.</param>
/// <param name="value">The to-be-set document title value.</param>
[DynamicDependency(nameof(GetDocumentTitle))]
public static void SetDocumentTitle(DependencyObject obj, string value) => obj.SetValue(DocumentTitleProperty, value);

/// <summary>
/// Handles changes to the <see cref="DocumentTitleProperty">DocumentTitle Attached Property</see>, ensures the underlying
/// <see cref="CoreWebView2"/> is initialized before subscribing to the <see cref="CoreWebView2.DocumentTitleChanged"/> event
/// and sets the initial title on the attached property.
/// </summary>
/// <param name="sender">The <see cref="DependencyObject"/> on which the property value changed.</param>
/// <param name="e">The <see cref="DependencyPropertyChangedEventArgs"/> event data.</param>
/// <exception cref="InvalidOperationException">Thrown if the attached property is applied to an object that is not a <see cref="WebView2"/> control.</exception>
private static async void OnDocumentTitleChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
if (sender is not WebView2 control)
{
throw new InvalidOperationException("The attached property 'DocumentTitle' can only be applied to a WebView2 control.");
}

if (control.CoreWebView2 is null)
{
await control.EnsureCoreWebView2Async();
}

// If CoreWebView2 is still null after attempting to ensure it, early return.
if (control.CoreWebView2 is null)
{
return;
}

// Remove previous event handler
control.CoreWebView2.DocumentTitleChanged -= OnCoreDocumentTitleChanged;

// Ensure we don't double-subscribe the Unloaded handler
control.Unloaded -= OnControlUnloaded;

// Subscribe to track document title changes and to clean up on Unloaded
control.CoreWebView2.DocumentTitleChanged += OnCoreDocumentTitleChanged;
control.Unloaded += OnControlUnloaded;

// Set initial value. CoreWebView2.DocumentTitle Property will either have the current title or be an empty string, never null.
SetDocumentTitle(control, control.CoreWebView2.DocumentTitle);
}

Copilot AI Mar 11, 2026

Copy link

Choose a reason for hiding this comment

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

DocumentTitleProperty is also used for both subscription management (property-changed callback) and for publishing the current title (OnCoreDocumentTitleChanged calls SetDocumentTitle). Updating the title will re-enter OnDocumentTitleChanged, causing repeated EnsureCoreWebView2Async() calls and re-subscribing/unsubscribing handlers on every title update (and can lead to re-entrancy loops depending on DP change semantics). Consider introducing a separate attached boolean to enable tracking, and keep DocumentTitleProperty as a pure state value that can be updated without running the subscription setup code.

Copilot uses AI. Check for mistakes.
Comment on lines +52 to +55
if (sender is not WebView2 control)
{
throw new InvalidOperationException("The attached property 'IsNavigating' can only be applied to a WebView2 control.");
}

Copilot AI Mar 11, 2026

Copy link

Choose a reason for hiding this comment

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

Throwing InvalidOperationException from an attached-property changed callback can crash apps due to style/template misuse or unexpected runtime values. Other attached-property implementations in this repo typically no-op (or log) when the target type doesn't match (e.g., TextBoxExtensions.OnInputReturnTypeChanged). Consider replacing the throw with a graceful return (optionally logging in debug) to keep the attached property safe to apply in XAML.

Copilot uses AI. Check for mistakes.
Comment on lines +140 to +170
private static async void OnDocumentTitleChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
if (sender is not WebView2 control)
{
throw new InvalidOperationException("The attached property 'DocumentTitle' can only be applied to a WebView2 control.");
}

if (control.CoreWebView2 is null)
{
await control.EnsureCoreWebView2Async();
}

// If CoreWebView2 is still null after attempting to ensure it, early return.
if (control.CoreWebView2 is null)
{
return;
}

// Remove previous event handler
control.CoreWebView2.DocumentTitleChanged -= OnCoreDocumentTitleChanged;

// Ensure we don't double-subscribe the Unloaded handler
control.Unloaded -= OnControlUnloaded;

// Subscribe to track document title changes and to clean up on Unloaded
control.CoreWebView2.DocumentTitleChanged += OnCoreDocumentTitleChanged;
control.Unloaded += OnControlUnloaded;

// Set initial value. CoreWebView2.DocumentTitle Property will either have the current title or be an empty string, never null.
SetDocumentTitle(control, control.CoreWebView2.DocumentTitle);
}

Copilot AI Mar 11, 2026

Copy link

Choose a reason for hiding this comment

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

OnDocumentTitleChanged is async void and awaits EnsureCoreWebView2Async() without any exception handling or a post-await lifecycle check. If initialization fails (or the control unloads while awaiting), exceptions may surface on the dispatcher and/or event handlers may be attached to an already-unloaded control. Consider wrapping the await in try/catch (with logging) and verifying the control is still loaded before subscribing and setting the initial value.

Copilot uses AI. Check for mistakes.
Comment on lines +96 to +184
private static void OnNavigationStarting(WebView2 sender, CoreWebView2NavigationStartingEventArgs args)
=> SetIsNavigating(sender, true);

private static void OnNavigationCompleted(WebView2 sender, CoreWebView2NavigationCompletedEventArgs args)
=> SetIsNavigating(sender, false);

#endregion

#region DependencyProperty: DocumentTitle
/// <summary>
/// Identifies the <see cref="DocumentTitleProperty">DocumentTitle Attached Property</see> in Xaml.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown if the attached property is applied to an object that is not a <see cref="WebView2"/> control.</exception>
public static DependencyProperty DocumentTitleProperty { [DynamicDependency(nameof(GetDocumentTitle))] get; } = DependencyProperty.RegisterAttached(
"DocumentTitle",
typeof(string),
typeof(WebView2Extensions),
new PropertyMetadata(string.Empty, OnDocumentTitleChanged));

/// <summary>
/// Gets the value of the <see cref="DocumentTitleProperty">DocumentTitle Attached Property</see> for the specified <see cref="DependencyObject"/>.
/// </summary>
/// <param name="obj">The object from which to get the property value.</param>
/// <returns>The document title of the WebView2 control.</returns>
[DynamicDependency(nameof(SetDocumentTitle))]
public static string GetDocumentTitle(DependencyObject obj) => (string)(obj.GetValue(DocumentTitleProperty) ?? string.Empty);

/// <summary>
/// Sets the value of the <see cref="DocumentTitleProperty">DocumentTitle Attached Property</see> for the specified <see cref="DependencyObject"/>.<br/>
/// When set, enables automatic tracking of document title changes on the <see cref="WebView2"/> control.
/// </summary>
/// <param name="obj">The object on which to set the property value.</param>
/// <param name="value">The to-be-set document title value.</param>
[DynamicDependency(nameof(GetDocumentTitle))]
public static void SetDocumentTitle(DependencyObject obj, string value) => obj.SetValue(DocumentTitleProperty, value);

/// <summary>
/// Handles changes to the <see cref="DocumentTitleProperty">DocumentTitle Attached Property</see>, ensures the underlying
/// <see cref="CoreWebView2"/> is initialized before subscribing to the <see cref="CoreWebView2.DocumentTitleChanged"/> event
/// and sets the initial title on the attached property.
/// </summary>
/// <param name="sender">The <see cref="DependencyObject"/> on which the property value changed.</param>
/// <param name="e">The <see cref="DependencyPropertyChangedEventArgs"/> event data.</param>
/// <exception cref="InvalidOperationException">Thrown if the attached property is applied to an object that is not a <see cref="WebView2"/> control.</exception>
private static async void OnDocumentTitleChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
if (sender is not WebView2 control)
{
throw new InvalidOperationException("The attached property 'DocumentTitle' can only be applied to a WebView2 control.");
}

if (control.CoreWebView2 is null)
{
await control.EnsureCoreWebView2Async();
}

// If CoreWebView2 is still null after attempting to ensure it, early return.
if (control.CoreWebView2 is null)
{
return;
}

// Remove previous event handler
control.CoreWebView2.DocumentTitleChanged -= OnCoreDocumentTitleChanged;

// Ensure we don't double-subscribe the Unloaded handler
control.Unloaded -= OnControlUnloaded;

// Subscribe to track document title changes and to clean up on Unloaded
control.CoreWebView2.DocumentTitleChanged += OnCoreDocumentTitleChanged;
control.Unloaded += OnControlUnloaded;

// Set initial value. CoreWebView2.DocumentTitle Property will either have the current title or be an empty string, never null.
SetDocumentTitle(control, control.CoreWebView2.DocumentTitle);
}

/// <summary>
/// Handles the <see cref="CoreWebView2.DocumentTitleChanged"/> event and updates
/// the <see langword="string"/> value of the <see cref="DocumentTitleProperty">DocumentTitle Attached Property</see>.
/// </summary>
/// <param name="sender">The <see cref="CoreWebView2"/> instance that raised the event.</param>
/// <param name="args">Event data.</param>
private static void OnCoreDocumentTitleChanged(CoreWebView2 sender, object args)
{
if (sender.Owner is WebView2 control)
{
// CoreWebView2.DocumentTitle Property will either have the current title or be an empty string, never null.
SetDocumentTitle(control, sender.DocumentTitle);
}

Copilot AI Mar 11, 2026

Copy link

Choose a reason for hiding this comment

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

This introduces new observable behavior (attached properties that mirror navigation state and document title) but there are no runtime tests validating it. There are existing WebView2 runtime tests under src/Uno.UI.RuntimeTests—consider adding coverage that verifies IsNavigating toggles and DocumentTitle updates when navigating / changing document title, so regressions in event wiring or lifecycle cleanup are caught.

Copilot generated this review using guidance from organization custom instructions.
@github-actions

Copy link
Copy Markdown
Contributor

This PR is stale because it has been open 60 days with no activity. Remove stale label or comment or it will be closed in 10 days.

@github-actions github-actions Bot added the stale This item has been marked as stale and will be closed if there is no activity. label May 15, 2026
@github-actions

Copy link
Copy Markdown
Contributor

This PR was closed because it has been stalled for 10 days with no activity.

@github-actions github-actions Bot closed this May 25, 2026
@MartinZikmund MartinZikmund removed the stale This item has been marked as stale and will be closed if there is no activity. label Jun 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

platform/android 🤖 Categorizes an issue or PR as relevant to the Android platform

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[WebView2] Event DocumentTitleChanged has always null argument instead of the new Value

7 participants