C# System.Windows.Controls.WebBrowser WPF的NullReferenceException

C# System.Windows.Controls.WebBrowser WPF的NullReferenceException,c#,webbrowser-control,mshtml,dom,C#,Webbrowser Control,Mshtml,Dom,我有一个C#WPF应用程序,它带有一个名为wB的web浏览器控件(System.Windows.Controls.WebBrowser)。它应该显示一个本地html文件,以及从中解析的一些信息 我得到了一个NullReferenceException,因为它在最后一行(IHTMLELELEmentCollection data=hDoc.body.children as IHTMLElementCollection)中表示body为null,代码如下: wB.Navigate(new Uri(f

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

我得到了一个NullReferenceException,因为它在最后一行(IHTMLELELEmentCollection 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,而在第二个示例中显示为罚款

Edit1
该方法被标记为[StatThread]…因此我认为并发性不会成为问题…

这是因为
Navigate()
方法是异步的-在第二个示例中,您确认MessageBox刚好有足够的时间完成,因此它可以工作-但不可靠


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

这是因为
Navigate()
方法是异步的-在第二个示例中,您确认MessageBox刚好有足够的时间完成,因此它可以工作-但不可靠

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

您应该使用

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;
}
你应该使用

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