概述
WPF 和 Winform 是兩個單獨的平臺,但二者又都是基於 .NET 4.0 以上版本開發的,所以很多.NET開發人員就開始研究如何在WPF中使用Winform。微軟已經架設了兩個開發平臺的之間的通信橋樑,目前爲止二者相互轉換使用已經相當成熟了,今天主要給大家講講如何在這兩個平臺下調用 ComponentOne 的控件。
本文主要用 FlexReport .NET報表控件,作爲介質進行兩個平臺的鏈接
Step 1
首先,我們還是把兩個平臺的基本通信通道搭建起來,很簡單,網上有很多步驟,總結起來主要分三步:
- 添加兩個引用:WindowsFormsIntegration.dll(負責整合WPF和Windows)、System.Windows.Forms.
- 在 XAML文件中添加兩個引用(粗體部分):
<Window x:Class="CrossBowDemo.MainWindow"
xmlns:wfi ="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"
xmlns:wf ="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Hosting Windows Forms Control In WPF"
Height="300"
Width="650"
ResizeMode="NoResize"
Loaded="WindowLoadedHandler">
< /Window>
解釋一下,這段代碼真正起作用的是這個引用WindowsFormsIntegration.dll,而這個引用System.Windows.Forms 指的是Winform裏面的微軟的原生態控件,所以在用到ComponentOne時,可以不引用它。
我們先看一個示例:通過微軟原生態控件在WPF中使用Winform,代碼如下:
<wfi:WindowsFormsHost>
<wf:DataGridView x:Name="Dg" Dock="Fill" SelectionMode="FullRowSelect">
</wf:DataGridView>
</wfi:WindowsFormsHost>
WindowsFormsHost其實是Winform在WPF的容器,所以Winform的控件顯示都要在這個容器裏面。
Setp2
上面我們說了,我們以FlexReport爲介質進行通信,那我們需要準備的幾個小步驟:
- Winform下FlexReport的模板
- 相關引用
注意:這裏面的引用是Winform的引用。同樣,我們需要在xmal中引用:
xmlns:cc11="clr-namespace:C1.Win.FlexViewer;assembly=C1.Win.FlexViewer.4"
在佈局中添加可供報表預覽的控件
<Grid>
<wfi:WindowsFormsHost>
<cc11:C1FlexViewerPane x:Name="flexViewerPane" ></cc11:C1FlexViewerPane>
</wfi:WindowsFormsHost>
</Grid>
Setp3
我們在後臺加載報表
private C1FlexReport _report;
public Window1()
{
InitializeComponent();
_report = new C1FlexReport();
// load report definition from resources
Assembly asm = Assembly.GetExecutingAssembly();
using (Stream stream = asm.GetManifestResourceStream("WpfApp1.Resources.FlexCommonTasks.flxr"))
_report.Load(stream, "Chart2D");
// assign report to the preview pane
flexViewerPane.DocumentSource = null;
flexViewerPane.DocumentSource = _report;
}
注:切記,這裏面的報表是Winform平臺下的
到這一步,我們工作完成了一大半,還差最後一步點石成金的步驟。很多人以爲在這就結束了,但是我們要考慮 ComponentOne License 授權的問題,如何把Winform 的授權在WPF下注冊,其實很簡單,因爲 .NET 的license機制一樣,我們只需用同樣的方式去註冊控件的license ,不過這裏推薦手動註冊,這很重要,因爲一不小心,就會報lc.exe=-1的錯誤
這裏我們都用到了
- C1FlexViewerPane
- C1FlexReport
所以我們在license文件中寫如下注冊信息
C1.Win.FlexReport.C1FlexReport,
C1.Win.FlexReport.4 C1.Win.FlexViewer.C1FlexViewerPane, C1.Win.FlexViewer.4
至此,我們就大功告成了。
示例源碼下載
本文中的示例源碼,請點擊此處下載
ComponentOne Enterprise:.NET開發的“瑞士軍刀”,功能全面、簡單易用的 Visual Studio 組件集