启动WebBrowser时CoreWebView2DownloadStartingEvent绑定报错:this不能为null
WebView2绑定DownloadStarting事件时触发Null异常
问题代码
CoreWebView2 WebView2; public TabViewItem CurrentTab; public TabContent() { this.InitializeComponent(); Browser.CoreWebView2.DownloadStarting += DownloadStarting_Event; } private void DownloadStarting_Event(CoreWebView2 sender, CoreWebView2DownloadStartingEventArgs args) { Debug.WriteLine("This is a test"); }
异常信息
引发异常:“System.ArgumentException”类型的异常在System.Private.CoreLib.dll中发生,但未在用户代码中处理
委托实例方法时不能使用null的“this”。
问题原因
构造函数执行时,Browser.CoreWebView2尚未完成初始化,处于null状态。直接对null对象的事件进行委托绑定,就会触发该异常。WebView2的CoreWebView2实例需要异步初始化,无法在控件构造阶段直接访问其属性或绑定事件。
解决方案
方案1:监听CoreWebView2初始化完成事件
在初始化完成后再绑定DownloadStarting事件:
public TabContent() { this.InitializeComponent(); // 先监听初始化完成事件 Browser.CoreWebView2InitializationCompleted += Browser_CoreWebView2InitializationCompleted; } private void Browser_CoreWebView2InitializationCompleted(object sender, CoreWebView2InitializationCompletedEventArgs e) { if (e.IsSuccess) { // 初始化成功后绑定下载事件 Browser.CoreWebView2.DownloadStarting += DownloadStarting_Event; } }
方案2:异步确保CoreWebView2初始化完成
利用EnsureCoreWebView2Async方法等待初始化完成,建议在控件Loaded事件中执行:
public TabContent() { this.InitializeComponent(); this.Loaded += TabContent_Loaded; } private async void TabContent_Loaded(object sender, RoutedEventArgs e) { // 等待CoreWebView2初始化完成 await Browser.EnsureCoreWebView2Async(); // 绑定下载事件 Browser.CoreWebView2.DownloadStarting += DownloadStarting_Event; }
内容的提问来源于stack exchange,提问作者mazo
相关产品推荐
相关产品推荐

