Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add WinForm User Control Into WPF so that I can reference it in the xaml.cs file

I am migrating part of a WinForms project into WPF.

I want to add an existing WinForms User Control into a WPF Form. The WinForm user control is called "TicketPrinter" and lives in the same project as the WPF form.

In my xaml I have this line:

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

And then I use it in my xaml here:

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

When I run the project the user control appears on the form as expected.

But when I go into the code behind xaml.cs file and try to access "ZapTicketPrinter" it is not available as a reference.

i.e.

I try using ZapTicketPrinter and it's not recognised.

I've also tried the following:

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

but get a null

What am I missing? How do I reference the name in my code?

like image 211
Paul H Avatar asked May 23 '12 09:05

Paul H


People also ask

Can you mix WinForms and WPF?

Yes you can, both Windows Forms within a WPF application, and WPF controls within Windows Forms.


1 Answers

provide x:Name instead of printer:name

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

MSDN Sample

Using code behind
http://msdn.microsoft.com/en-us/library/ms751761.aspx
Walkthrough: Hosting a Windows Forms Control in WPF

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

like image 149
JSJ Avatar answered Sep 29 '22 08:09

JSJ