Live Chat Icon For mobile
Live Chat Icon

How do I host a Windows Forms control in a WPF application ?

Platform: WPF| Category: Win32 in WPF

First make sure to add references to ‘System.Windows.Forms’ and ‘System.Windows.Forms.Integration’. Then you need to decide if you will use code, XAML or a combination of both to work with the Windows Forms controls. If you are strictly using code, you would write code similar to the following :


//Instantiate the hosting control
WindowsFormsHost host = new WindowsFormsHost();
//Instantiate the Windows Forms control, in this case a button
System.Windows.Forms.Button wfButton = 
  new System.Windows.Forms.Button();
wfButton.Text = 'Windows Forms Button';

// Add the Windows Forms button to the host control

// Add the host control to the WPF element that 
// you want to parent the control,
// in this case it’s a Grid

If you are using XAML, you still need to add the references to ‘System.Windows.Forms’ and ‘System.Windows.Forms.Integration’, but you will also need to add mapping statements to your XAML that will allow you to refer to the objects that live in these namespaces via XAML:


<?Mapping XmlNamespace='wfi' ClrNamespace='System.Windows.Forms.Integration' Assembly='WindowsFormsIntegration'?>
        <?Mapping XmlNamespace='wf' ClrNamespace='System.Windows.Forms' Assembly='System.Windows.Forms'?>

The ‘XMLNamespace’ property provides a way to create a tag that you can use as a namespace prefix in the XAML to refer to the controls within the ‘System.Windows.Forms’ and ‘System.Windows.Forms.Integration’ namespaces. To enable this, you must also create ‘xmlns’ properties in the XAML that maps back to these prefixes as given below :


        <Window x:Class='AvalonApplication17.Window1'
xmlns:wf='wf' Title='AvalonApplication17'
            Then you can use XAML to instantiate the WindowsFormsHost control and its subsequent child controls:
            <Grid x:Name='grid1'>
                    <wf:Button Text='Windows Forms Button'/>

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.