2012-05-23 67 views
5

我正在将WinForms项目的一部分迁移到WPF中。如何将WinForm用户控件添加到WPF中,以便我可以在xaml.cs文件中引用它

我想将现有的WinForms用户控件添加到WPF表单中。 WinForm用户控件称为“TicketPrinter”,并与WPF表单位于同一个项目中。

在我的XAML中我有这样一行:

xmlns:Printers="clr-namespace:Project.UserControls.Printers" 

然后,我用它在我的XAML浏览:

 <WindowsFormsHost Height="430" HorizontalAlignment="Left" Margin="468,12,0,0" Name="windowsFormsHost1" VerticalAlignment="Top" Width="324"> 
      <Printers:TicketPrinter Printers:Name="ZapTicketPrinter"> 
      </Printers:TicketPrinter> 
     </WindowsFormsHost> 
    </Grid> 
</Window> 

当我运行的用户控件显示表单上的项目如预期。

但是,当我进入xaml.cs文件后面的代码并尝试访问“ZapTicketPrinter”时,它不可用作参考。

我尝试使用ZapTicketPrinter,它不是认可。

我也试过如下:

TicketPrinter ticketPrinter = this.FindName("ZapTicketPrinter") as TicketPrinter; 

却得到了一个空

我缺少什么? 如何在我的代码中引用该名称?

回答

3

尝试使用下面的代码:

private void LoadWFUserControl() 
{ 
    // Initialize a Host Control which allows hosting a windows form control on WPF. Ensure that the WindowsFormIntegration Reference is present. 
    System.Windows.Forms.Integration.WindowsFormsHost host = 
     new System.Windows.Forms.Integration.WindowsFormsHost(); 

    // Create an object of your User control. 
    MyWebcam uc_webcam = new MyWebcam(); 

    // Assign MyWebcam control as the host control's child. 
    host.Child = uc_webcam; 

    // Add the interop host control to the Grid control's collection of child controls. Make sure to rename grid1 to appr 
    this.grid1.Children.Add(host); 
} 
相关问题