Embed WPF User Controls in WinForms Applications

WinForms and WPF are two different technologies. Both have pros and cons. However, we can intermix UI controls between them. So, we can support the functionality of WinForms and WPF in a single application by adding WPF controls in the WinForms application. We can also support the MVVM approach and Binding functionality of WPF in the WinForms application. To achieve this requirement, we must host a WPF UserControl in the WinForms application.

In this blog, we will see how to use a ComponentOne WPF control (C1FlexGrid and C1Rating) in a WinForms application.

Ready to Start Embedding WPF User Controls? Try ComponentOne Today!

Steps to Host WPF UserControl in Winforms

Add ElementHost Control

ElementHost is a WinForms control that can be used to host a Windows Presentation Foundation (WPF) element. To add ElementHost Control in Windows Form, you need to add the WindowsFormsIntegration.dll reference first.
Then you can drag ElementHost from the Toolbox and drop it into the Form.

Creating a WPF UserControl

You can create a WPF UserControl in the WinForms application. In the Solution Explorer of the project, right-click on the project node and select Add->New Item. Select UserControl (WPF) and create your own UserControl named "WpfUserControl.xaml".

Editing WPF UserControl

You can edit the WPF UserControl with some XAML code. You can add WPF controls like C1FlexGrid(WPF) and C1Rating into the WPF UserControl.

             xmlns:c1="http://schemas.componentone.com/winfx/2006/xaml" x:Class="WpfControlHost.WpfUserControl"
             d:DesignHeight="200" d:DesignWidth="500">
    <!--C1 WPF FlexGrid control-->
        <c1:C1FlexGrid x:Name="grid" ItemsSource="{Binding Songs}" MinRowHeight="50" Loaded="FlexgridLoaded" AutoGenerateColumns="False">
                <c1:Column Header="Track" Binding="{Binding Track}"/>
                <c1:Column Header="Duration" Binding="{Binding Duration}"/>
                <c1:Column Header="Size" Binding="{Binding Size}"/>
                <c1:Column Header="Rating" Binding="{Binding Rating}">
                            <!--C1 WPF C1Rating control-->
                            <c1:C1Rating Value="{Binding Rating}" RatedBrush="Yellow" HoveredBrush="Orange" VerticalAlignment="Center" ShowToolTip="False">

Hosting WPF UserControl on ElementHost

At last, host the WPF UserControl on ElementHost. First, rebuild your solution, so the WpfUserControl is visible in the Toolbox. Now, open the ToolBox, drag WpfUserControl from ToolBox and place it on your Form.

Finally, the WPF UserControl is hosted on a WinForms application where WPF controls (C1FlexGrid and C1Rating) are added to the hosted WPF UserControl.

For full implementation, download the sample.

Ready to Start Embedding WPF User Controls? Try ComponentOne Today!

comments powered by Disqus