WPF实战小技巧(四):在WPF中使用WebKit控件(含示例代码)
WebKit 是一个开源的浏览器引擎,可以用于程序内置浏览器的开发。开发时,需要将WebKit的相关文件都拷贝至项目文件,方便编程时调用,实现WebKit的功能。在WPF中使用WebKit时,添加好引用,就可以使用WebKit控件了。使用时一般有两种方法,一种是直接在MainWindow.xaml文件的界面布局中添加WebKit控件。另一种是编写代码,在程序启动后,绘制主窗体时添加WebKit控件
WebKit 是一个开源的浏览器引擎,可以用于程序内置浏览器的开发。开发时,需要将WebKit的相关文件都拷贝至项目文件,方便编程时调用,实现WebKit的功能。
在WPF中使用WebKit时,需要添加以下引用。
添加好引用后,就可以在WPF中使用WebKit控件了。使用时一般有两种方法,一种是直接在MainWindow.xaml文件的界面布局中添加WebKit控件。由于WebKit控件原生支持WinForm而非WPF,所以需要在WinFormsHost控件之上添加WebKit控件,才能使控件生效。
添加控件引用:
xmlns:wfi="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
xmlns:wf="clr-namespace:WebKit;assembly=WebKitBrowser"
添加WebKit控件:
<Grid Grid.Row="0" x:Name="grdViewerHost">
<WindowsFormsHost>
<wf:WebKitBrowser x:Name="Viewer"></wf:WebKitBrowser>
</WindowsFormsHost>
</Grid>
这样在绘制主窗体时,就可以直接调用WebKitBrowser对象了:
public MainWindow()
{
InitializeComponent();
this.Loaded+= new RoutedEventHandler(MainWindow_Loaded);
this.Closing+= new System.ComponentModel.CancelEventHandler(MainWindow_Closing);
}
private void MainWindow_Loaded(object sender, RoutedEventArgse)
{
Viewer.DocumentText = "";
}
另一种是编写代码,在程序启动后,绘制主窗体时添加WebKit控件。
在MainWindow.xaml文件添加布局:
<Grid Grid.Row="0" x:Name="grdBrowserHost"/>
在MainWindow_Loaded函数绘制控件:
webKitBrowser = new WebKit.WebKitBrowser();
webKitBrowser.BackColor= System.Drawing.Color.White;
webKitBrowser.Name ="webKitBrowser1";
webKitBrowser.TabIndex= 0;
System.Windows.Forms.Integration.WindowsFormsHost host = newSystem.Windows.Forms.Integration.WindowsFormsHost();
host.Child =webKitBrowser;
grdBrowserHost.Children.Add(host);
更多推荐
所有评论(0)