在 wpf 应用程序中使用 winforms webbrowser 导航到 url

Navigating to a url using a winforms webbrowser in a wpf application

我正在构建一个包含 WebBrowser 的 WPF 应用程序。我想在 webbrowser 中使用 Document.GetElementByID 方法,我的理解是在 WPF 中执行此操作的最简单方法是使用 winforms webbrowser 和 WindowsFormsIntegration(如果有更好的方法请告诉我)

我在导航到 URL 时遇到问题。 运行调试模式下的程序不会抛出任何错误,并且跳过导航代码仍然使我的网络浏览器具有以下属性:

wb1.ReadyState = Uninitialized
wb1.Url = null

我是否遗漏了导航到 url 的内容?我可以在 WPF 网络浏览器中使用 Document.GetElementById 方法吗?

xaml:

<Window x:Class="my program's main window"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
...
<WindowsFormsHost Name="wfh">
    <WindowsFormsHost.Child>
        <wf:WebBrowser/>
    </WindowsFormsHost.Child>
</WindowsFormsHost>

代码:

var wb1 = wfh.Child as System.Windows.Forms.WebBrowser;
wb1.Navigate("my url here");
while (wb1.ReadyState != System.Windows.Forms.WebBrowserReadyState.Complete)
{
    // this loop never ends because neither readystate nor wb1.Url ever change
}

向您的项目添加对 Microsoft.mshtml 的引用(从程序集 > 扩展)。然后使用 WPF WebBrowser 控件并将其 Document 属性 转换为 HTMLDocument:

<WebBrowser x:Name="webBrowser" Navigated="WebBrowserNavigated" />

后面的代码:

using mshtml;
...

webBrowser.Navigate("...");
...

private void WebBrowserNavigated(object sender, NavigationEventArgs e)
{
    var document = webBrowser.Document as HTMLDocument;
    ...
}