Skip to main content
 首页 » 编程设计

c#之System.Windows.Controls.WebBrowser WPF 的 NullReferenceException

2024年01月25日26mengfanrong

我有一个 C# WPF 应用程序,它带有一个名为 wB 的 Web 浏览器控件 (System.Windows.Controls.WebBrowser)。它应该显示本地 html 文件,以及从中解析的一些信息。

我得到一个 NullReferenceException,因为它在最后一行 (IHTMLElementCollection data = hDoc.body.children as IHTMLElementCollection) 中说 body 为 null,代码如下:

wB.Navigate(new Uri(file, UriKind.Absolute));                 
HTMLDocument hDoc = (HTMLDocumentClass)wB.Document; 
IHTMLElementCollection data = hDoc.body.children as IHTMLElementCollection; 

如果我这样做

wB.Navigate(new Uri(file, UriKind.Absolute));                 
HTMLDocument hDoc = (HTMLDocumentClass)wB.Document; 
System.Windows.MessageBox.Show("Loc:" + hDoc.url); 
IHTMLElementCollection data = hDoc.body.children as IHTMLElementCollection; 

一切正常。为什么 body 在第一个示例中显示为 null,但在第二个示例中显示正常?

编辑1 该方法被标记为 [STAThread]...所以我认为并发不会成为问题...

请您参考如下方法:

那是因为 Navigate() 方法是异步的 - 在第二个示例中,您确认 MessageBox 有足够的时间完成它,所以它可以工作 - 虽然不可靠。

相反,您应该订阅 DocumentCompleted事件并在回调中收集数据。