Is there any way to use Windows Forms components in WPF?
Yes , as long as you add references to the project to the following assemblies :
To use them use a WindowsFormsHost and add the components as children.
Example for MaskedTextBox
:
<Window x:Class="TesteWpf.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
Title="MainWindow" Height="350" Width="525">
<Grid>
<WindowsFormsHost>
<wf:MaskedTextBox Mask="00/00/0000">
</wf:MaskedTextBox>
</WindowsFormsHost>
</Grid>
</Window>
Example for Chart
:
Add a reference to assembly System.Windows.Forms.DataVisualization
MainWindow.xaml
<Window x:Class="TesteWpf.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:winformchart="clr-namespace:System.Windows.Forms.DataVisualization.Charting;assembly=System.Windows.Forms.DataVisualization"
Title="MainWindow" Height="350" Width="525">
<Grid>
<WindowsFormsHost>
<winformchart:Chart x:Name="Chart" Dock="Fill">
<winformchart:Chart.Series>
<winformchart:Series Name="series" ChartType="Line"/>
</winformchart:Chart.Series>
<winformchart:Chart.ChartAreas>
<winformchart:ChartArea/>
</winformchart:Chart.ChartAreas>
</winformchart:Chart>
</WindowsFormsHost>
</Grid>
</Window>
MainWindow.xaml.cs
using System.Collections.Generic;
using System.Windows;
using System.Windows.Forms.DataVisualization.Charting;
namespace TesteWpf
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var graphicValues = new Dictionary<int, double>();
for (int i = 0; i < 10; i++)
{
graphicValues.Add(i, 10 * i);
}
Chart.DataSource = graphicValues;
Chart.Series["series"].XValueMember = "Key";
Chart.Series["series"].YValueMembers = "Value";
}
}
}
Are there disadvantages when using WF components in WPF?
- Mixing of technologies, there are some issues to consider , one simply because the two technologies do not come together smoothly, other because they are either design decisions or design differences between Windows Forms and WPF.
It is more advantageous to create a WPF component than to use the existing one in WF.
- For the above reasons.
- If you have the availability and ingenuity to create it.