WPF & Datargidview Control
The Windows Forms DataGridView control may be hosted in a WPF form using a <WindowsFormsHost> tag(in fact any Windows Forms Control may be hosted within this tag, which provides a solution to the lack of a WPF Data Grid control).
The following XAML and VB.Net code was done using Visual Studio 2005 .
In a WPF Windows application:
- add a reference to WindowsFormsIntegration (WindowsFormsIntegration.dll)
- add a reference to System.Windows.Forms:
xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms" ...
- add the following XAML to host the DataGridView control
<StackPanel>
<WindowsFormsHost Width="200" Height="200">
<wf:DataGridView x:Name="dgv"> </wf:DataGridView>
</WindowsFormsHost>
</StackPanel>
Note: it appears that the <WindowsFormsHost> should have Width and Height attributes to ensure that the DataGridView will render with scrollbars
- Build the Project
In the associated code view for the XMAL(Windows.xaml.vb) :
- Add the following code to the Window1_Loaded event handler:
'Use the Authors table in the Pubs database
Dim conn As New System.Data.SqlClient.SqlConnection("integrated security=true;database=pubs")
Dim da As New System.Data.SqlClient.SqlDataAdapter("select * from employee", conn)
Dim ds As New System.Data.DataSetda.Fill(ds)
Me.dgv.DataSource = ds.Tables(0)
Me.dgv.DataMember = ds.Tables(0).TableName
Me.dgv.ScrollBars = System.Windows.Forms.ScrollBars.Both
Me.dgv.Visible = True
Run the program to display the WPF with the DataGridView.
Note that <WindowsFormsHost> may only contain one Windows Forms Control. Use multiple <WindowsFormsHost> tags or create a Windows Forms User Control with the desired layout and host in using in <WindowsFormsHost>. Also, the DataGridView will not render with any WPF styles that may have defined.