2012-05-23 13 views
5

Sto migrando parte di un progetto WinForms in WPF.Come aggiungere WinForm User Control a WPF in modo che possa fare riferimento nel file xaml.cs

Desidero aggiungere un controllo utente WinForms esistente in un modulo WPF. Il controllo utente WinForm si chiama "TicketPrinter" e risiede nello stesso progetto del modulo WPF.

Nel mio XAML ho questa linea:

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

E poi lo uso nel mio XAML qui:

 <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> 

Quando eseguo il progetto appare il controllo utente sul modulo come previsto .

Ma quando vado nel codice dietro il file xaml.cs e provo ad accedere a "ZapTicketPrinter" non è disponibile come riferimento.

cioè

provo utilizzando ZapTicketPrinter e non è riconosciuto.

Ho anche provato la seguente:

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

ma ottenere un nulla

Che cosa mi manca? Come faccio a fare riferimento al nome nel mio codice?

risposta

7

forniscono x: Nome invece di stampante: nome

<WindowsFormsHost> 
    <Printers:TicketPrinter x:Name="ZapTicketPrinter"/> 
</WindowsFormsHost> 

MSDN campione

Utilizzando codice dietro
http://msdn.microsoft.com/en-us/library/ms751761.aspx
Walkthrough: Hosting a Windows Forms Control in WPF

Utilizzando XAML
http://msdn.microsoft.com/en-us/library/ms742875.aspx
Walkthrough: Hosting a Windows Forms Control in WPF by Using XAML

+0

@ConnorMcGuinness Ho aggiornato i link – Athafoud

3

Provare a utilizzare seguente codice:

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); 
} 
Problemi correlati