The first thing we need to do (after creating a new WPF project) is add few references.
1. Add reference to System.Windows.Forms and WindowsFormsIntegration.
Once these two references are added, we have access to all windows forms controls and access to the components that will allow us to embed them in WPF.
2. In the WPF Tool Box, we can see WindowsFormsHost control
This object is glue layer between WPF and Windows Forms. The WindowsFormsHost is a Framework element, so it can be added to anything in WPF that can take an element. But it has a property Child which takes in a System.Windows.Forms.Control - and this is the control that will be embedded.
Drag and Drop the WindowsFormsHost Control in WPF Window.
Our XAML is going to be extremely simple:
<Window x:Class = "Window1" >
xmlns= "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="278" Width="587"
<Grid>
<WindowsFormsHost Name="WindowsFormsHost1" >
</Grid>
</Window>
3. Add New Windows Forms to the WPF application
Add DataGridView and add few columns and the windows form would look like as follows:
Set EnableVisualStyles()of Windows Forms in the New Method.
Public Class Form1
Public Sub New()
' This call is required by the Windows Form Designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
Forms.Application.EnableVisualStyles()
End Sub
End Class
4. After the Form is ready, all we need is adding the form as the child for the WindowsFormsHost control.
In the WPF Window Load event add the following:
Private Sub Window1_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
Dim Frm As New Form1
Frm.TopLevel = False 'Very important ..
WindowsFormsHost1.Child = Frm
Frm = Nothing
End Sub
5. See the result
That’s All!!!!!!
And that is about it for Hosting Windows Forms or Windows Forms Controls inside of WPF Window.
No comments:
Post a Comment