2012-05-23 19 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); 
} 
相關問題