System.Windows.Controls.WebBrowser WPF的NullReferenceException

时间:2011-11-21 13:47:25

标签: c# webbrowser-control mshtml dom

我有一个名为wB的Web浏览器控件(System.Windows.Controls.WebBrowser)的C#WPF应用程序。它应该显示一个本地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;

一切正常。为什么在第一个例子中身体显示为空,但在第二个例子中显示为空?

EDIT1 该方法被标记为[STAThread] ...所以我认为并发不会是一个问题......

2 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分:3)

你应该使用

wb.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(wb_DocumentCompleted);

因此,您可以确定已加载文档:

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;
}