views:

27

answers:

1

I'm trying to integrate a WinForms Form inside a WPF XAML page. I have seen examples of putting Windows Forms controls using WindowsFormsHost, but not for integrating a whole form.

Is there a way to do it? The Windows form is hosted inside the WPF application and I'm currently able to load it as a new window but not inside the XAML page.

+1  A: 

To put a WinForms form inside a WindowsFormsHost tag in a WPF Form is an error. But you can instantiate a new form from any WPF Project. Here's how:

Say you have two projects "WinFormProj" and "WPFProj". WinFormProj has a form called "Login".

First add a reference in the WPFProj project to WinFormProj.

Then behind any event in any WPFProj element, do this:

var winFormWindow = new WinFormProj.Login();  
winFormWindow.Show();  
// or  
windFormWindow.ShowDialog();  

If that won't do, you can convert your WinForms form to a user control which will exist just great in a WindowsFormsHost WPF tag. To do that, it is often as simple as ...

Go to the class declaration and change:

public class Login : Form

to

public class Login : UserControl

Next, in your WPF form, add the WinForms project as an xml namespace:

xmlns:winForms="clr-namespace:WinFormsProj;assembly=WinFormsProj"

And finally, add this to your Grid/StackPanel/Whatever where you want the user control to be hosted:

<WindowsFormsHost Name="LoginControl">
    <winForms:LogIn />
</WindowsFormsHost>

Pretty simple once you demystify it.

Rap