NullReferenceException with System.Windows.Controls.WebBrowser WPF

心已入冬 提交于 2019-12-23 03:29:09

问题


I have a C# WPF application with a web browser control (System.Windows.Controls.WebBrowser) called wB. It is supposed to display a local html file, and some information parsed from it.

I get the a NullReferenceException as it says body is null in the last line (IHTMLElementCollection data = hDoc.body.children as IHTMLElementCollection) with the following code:

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

If I do

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;

Everything works fine. Why is body showing up null in the 1st example, but fine for the second?

Edit1 The method is marked as [STAThread]...so I thought concurrency wouldn't be an issue...


回答1:


You should use

wb.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(wb_DocumentCompleted);

So you can be sure the document loaded already:

private void wb_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
  WebBrowser wb = sender as WebBrowser;
  HTMLDocument hDoc = (HTMLDocumentClass)wB.Document;
  IHTMLElementCollection data = hDoc.body.children as IHTMLElementCollection;
}



回答2:


That's because the Navigate() method is asynchronous - in the second example you confirming the MessageBox is just enough time for it having completed, so it works - not reliably though.

Instead you should subscribe to the DocumentCompleted event and do your data collection in the callback.



来源:https://stackoverflow.com/questions/8212825/nullreferenceexception-with-system-windows-controls-webbrowser-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!