You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WPF WebView2首次更新Source属性后绑定丢失问题咨询

WebView2 Source属性绑定丢失问题解答

问题根因

你遇到的是1.0.864.35及更早版本WPF封装的WebView2的已知缺陷,并非你的实现逻辑存在问题。
该版本WebView2内部处理导航流程时,会直接对Source依赖属性赋值本地值,根据WPF依赖属性的优先级规则,本地赋值的优先级高于绑定源,所以会直接清除原有的绑定表达式,导致后续属性变更无法通知到控件。

解决方案

方案1:升级NuGet包(最简便)

微软在1.0.902.49及后续版本的WebView2 SDK中已经修复了该问题,直接将你的Microsoft.Web.WebView2 NuGet包升级到1.0.902.49或更高版本即可,原有代码无需做任何改动。

方案2:使用附加属性中转(兼容旧版本)

如果因项目限制暂时无法升级SDK,可以通过附加属性替代原生Source绑定,避免内部赋值覆盖绑定:

public static class WebView2Extensions
{
    public static readonly DependencyProperty BindableSourceProperty =
        DependencyProperty.RegisterAttached(
            "BindableSource", 
            typeof(string), 
            typeof(WebView2Extensions),
            new PropertyMetadata(string.Empty, OnBindableSourceChanged));

    public static string GetBindableSource(DependencyObject obj)
    {
        return (string)obj.GetValue(BindableSourceProperty);
    }

    public static void SetBindableSource(DependencyObject obj, string value)
    {
        obj.SetValue(BindableSourceProperty, value);
    }

    private static void OnBindableSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (d is WebView2 webView && e.NewValue is string url)
        {
            if (webView.CoreWebView2 != null)
            {
                webView.CoreWebView2.Navigate(string.IsNullOrEmpty(url) ? "about:blank" : url);
            }
            else
            {
                // 等待CoreWebView2初始化完成后再导航
                webView.CoreWebView2InitializationCompleted += (s, args) =>
                {
                    if (args.IsSuccess)
                    {
                        webView.CoreWebView2.Navigate(string.IsNullOrEmpty(url) ? "about:blank" : url);
                    }
                };
                webView.EnsureCoreWebView2Async();
            }
        }
    }
}

视图层绑定改为使用附加属性:

<wpf:WebView2 x:Name="WebView" Grid.Row="1" 
              local:WebView2Extensions.BindableSource="{Binding Url}"/>

使用该方案可以直接绑定Url属性,不需要额外定义WebViewUri属性。

内容的提问来源于stack exchange,提问作者raznagul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 14:33:03