Winform的WebBrowser相對靈活一些。接下來把操作步驟分享給大家。
一、 引入dll
System.Windows.Forms.dll和WindowsFormsIntegration.dll。
兩個都是.NET框架下的dll,不需要額外下載。
二、 向界面中添加定義的控件(將導入的dll引入到界面中啦)。Xaml代碼部分:
xmlns:wf ="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
xmlns:wfi="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"
//插入Winform的WebBrowser控件
<wfi:WindowsFormsHost Name="winFormsContainer">
<wf:WebBrowser x:Name="webBrowser1"/>
</wfi:WindowsFormsHost>
注意:只有在WindowsFormsHost標籤下才能插入WinForm控件。當然你也可以插入其他WinForm控件
三、cs代碼段
string html=“你需要展示的html代碼”;
//調用引入的webBrowser1
webBrowser1.Navigate("about:blank"); //一定要創建一個空白界面。不然即使寫入html成功顯示也不能再次回讀其中內容。
webBrowser1.Document.OpenNew(false);
webBrowser1.Document.Write(html);
webBrowser1.Refresh();
//這個時候你可以寫js代碼來操縱你想要的一切(如下)
String newContent = webBrowser1.Document.GetElementById("container").InnerHtml;
//也可以webBrowser寫入html時加入一些css樣式(真的很方便!)