WPF interoperability with Windows Forms
In October 24th 2009, I got a chance to attend MS Community Techdays at Trivandrum. One of the session was WPF interoperability with Windows Forms. By using this we can use WPF controls in Classic Windows based applications. For this you require a special control called “ElementHost“, if you developed any Windows based application in VS 2008, this control will be available under WPF interoperability tab. If you add this control to a Windows Form, Visual Studio will automatically updates the References list. It will add few more references like PresentationCore, PresentationFrameWork, UIAutomationProvider, WindowsBase, WindowsFormsIntegration. Then you can add a WPF User Control to a Windows Form.
- Create a Windows Application Project.
- Right Click on the Project Node in the solution explorer, select Add New Item, and Select User Control(WPF) from Add New Item Dialog.
- In the User Contol I wrote some code to change the Color on MouseMove and I wrote the click event in the Codebehind.
- Build the Project.
- Drag and Drop, ElementHost control from WPF interoperability tab.
- You can Set the host the WPF usercontrol either by selecting Select Host Content from Smart Menu, or by Setting the Child Property in the Property List. (The control will be populated in the List only if you build the application, after you added the control.)
- You can also do it in runtime by setting Child Property of the Element Host control.
XAML Code
<Grid>
<Grid.Resources>
<Style TargetType="Button" x:Key="CustomButton">
<Setter Property="FontSize" Value="15" />
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="FontSize" Value="20" />
</Trigger>
</Style.Triggers>
</Style>
</Grid.Resources>
<Button Style="{StaticResource CustomButton}"
Content="Hello World"
Click="Button_Click">
</Button>
</Grid>
Code behind – C#
private void Button_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("WPF UserControl Event");
}
private void Form1_Load(object sender, EventArgs e)
{
SampleWPFCtrl ctrl1 = new SampleWPFCtrl();
this.elementHost1.Child = ctrl1;
}

WPF Usercontol Control in Windows Form
Happy Coding
