概述

WPF 和 Winform 是两个单独的平台,但二者又都是基于 .NET 4.0 以上版本开发的,所以很多.NET开发人员就开始研究如何在WPF中使用Winform。微软已经架设了两个开发平台的之间的通信桥梁,目前为止二者相互转换使用已经相当成熟了,今天主要给大家讲讲如何在这两个平台下调用 ComponentOne 的控件。

本文主要用 FlexReport .NET报表控件,作为介质进行两个平台的链接

Step 1

首先,我们还是把两个平台的基本通信通道搭建起来,很简单,网上有很多步骤,总结起来主要分三步:

  1. 添加两个引用:WindowsFormsIntegration.dll(负责整合WPF和Windows)、System.Windows.Forms.
  2. 在 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为介质进行通信,那我们需要准备的几个小步骤:

  1. Winform下FlexReport的模板
  2. 相关引用

相关引用

注意:这里面的引用是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

至此,我们就大功告成了。

示例源码下载

本文中的示例源码,请点击此处下载