标签:
the first thing that we need to do (after creating a new WPF project) is add a few references. You can do this by by right-clicking on the references folder in the solution explorer, and choosing "Add Reference":
Then you will get a dialog like this:
There are two .NET components you will want to add - first, System.Windows.Forms
, and then, all the way at the bottom (after you get to this dialog a second time),WindowsFormsIntegration
.
Once those two references are added, we have access to all of the WinForms controls, and access to the components that will allow us to embed them in WPF. So now lets get started on some code. First, we are going to take a look at embedding theDataGridView
using C#, so this means our XAML is going to be extremely simple:
<Window x:Class="WinFormsInWPF.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Using WinForms In WPF" Height="300" Width="300">
<Grid x:Name="_Container">
<Grid.RowDefinitions>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="20"></RowDefinition>
</Grid.RowDefinitions>
<Button Grid.Row="1" Click="ClearClick" HorizontalAlignment="Right">
Clear All Rows
</Button>
</Grid>
</Window>
As you might notice, there is no reference to the DataGridView
anywhere in that XAML. All we have is a grid with two rows, and a button in the second row. This is because we are going to be shoving in the DataGridView
into the first row using C# code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Forms.Integration;
namespace WinFormsInWPF
{
public partial class Window1 : Window
{
private System.Windows.Forms.DataGridView _MyDataGrid;
private WindowsFormsHost _MyHost;
public Window1()
{
InitializeComponent();
_MyHost = new WindowsFormsHost();
_MyDataGrid = new System.Windows.Forms.DataGridView();
System.Windows.Forms.DataGridViewColumn col;
col = new System.Windows.Forms.DataGridViewColumn();
col.CellTemplate = new System.Windows.Forms.DataGridViewTextBoxCell();
col.Name = "Col 1";
_MyDataGrid.Columns.Add(col