We know that the windowsformhost class is required to add winform controls on the WPF interface. How can I add a WPF control on the winform interface? Are there any similar classes? Obviously, elementhost is defined to embed the WPF element in the winform application. It inherits from system. Windows. Forms. Control and is a winform control, but it knows how to display WPF content.
Next we will demonstrate how to use elementhost to display a WPF control -- button and make a simple comparison with the display of the button in winform (XP environment ).
1. Create a standard winform project, find the "WPF interoperability" project in the toolbar, select elementhost, and drag it to form, as shown in Figure 1:
Figure 1 drag elementhost to form
2. Adjust the elementhost size. By default, the WPF control occupies all the space given to elementhost. In addition, let's take a look at the references of the project. After you drag elementhost, necessary WPF assembly (presentationframework, presentationcore, windowbase, etc.) will be automatically added ).
3. Drag a winform button to form and change the content of the button to "button in winform", as shown in Figure 2:
Figure 2 Add a winform button
4. the WPF control can only be added to elementhost in the background code. We create a WPF control in the form constructor, as shown in the following code snippet:
Public partial class form1: Form
{
Public form1 ()
{
Initializecomponent ();
// Create a WPF button
System. Windows. Controls. Button BTN = new system. Windows. Controls. Button ();
BTN. content = "button in WPF ";
// Add it to elementhost
Elementhost. Child = BTN;
}
}
The child attribute of elementhost is of the uielement type. Therefore, it can be set to any uielement object.
5. Press F5 to run the winform application. The display of the WPF button control and the winform button control is 3. We can see that the default fonts of the two buttons are obviously different.
Figure 3 display of two buttons