C# WPF控件的铸造

C# WPF控件的铸造,c#,wpf,datagridview,casting,wpf-controls,C#,Wpf,Datagridview,Casting,Wpf Controls,我使用WindowsFormHost以便能够在WPF应用程序中使用gridview (从这个开始,) 并以 public WindowsFormsHost HOST = new WindowsFormsHost(); 我的gridview作为 System.Windows.Forms.DataGridView gridview = new System.Windows.Forms.DataGridView(); (不要忘记参考资料,请按此处-) 我用数据表填充它,如下所示 table

我使用WindowsFormHost以便能够在WPF应用程序中使用gridview (从这个开始,)

并以

 public WindowsFormsHost HOST = new WindowsFormsHost();
我的gridview作为

 System.Windows.Forms.DataGridView gridview = new System.Windows.Forms.DataGridView(); 
(不要忘记参考资料,请按此处-)

我用数据表填充它,如下所示

 table = new System.Data.DataTable();
            table.Columns.Add("Object ID");
            foreach (string column in columns)
            {
                table.Columns.Add(column);

            }
            foreach (string row in rows)
            { 
                drow = table.NewRow();
                tit = row.Substring(0, row.IndexOf('$'));
                drow[0] = tit.IndexOf('&') > -1 ? tit.Substring(tit.IndexOf('&') + 1) : tit;
                table.Rows.Add(drow);

            }

            //making the native control known to the WPF application
            HOST.Child = gridview;
            //Displaying the column headers of the listbox(assigned above). 
            gridview.DataSource = table.DefaultView;
但是,当我将gridview添加到WPF窗口时

  this.Children.Add(gridview);   //error at this line
我听到一个错误说

 cannot convert from 'System.Windows.Forms.DataGridView' to 'System.Windows.UIElement' 
为什么会这样?
我的意思是我可以做些什么来纠正这个问题?

DataGridView
是一个
WinForms
控件。所以不能直接将其添加到WPF控件的子级。而是添加
WindowsFormsHost
实例,如下所示:

RootGrid.Children.Add(HOST);

这个问题和当前的答案严重吗???究竟为什么您要导入WindowsForms dll并向WPF应用程序添加CPU密集型
WindowsFormsHost
元素,以便您可以使用
DataGridView
控件?您会发现,仅使用等效的WPF控件要好得多:
DataGrid


通过查看MSDN上的页面,您可以找到有关
DataGrid
类的所有信息。本页有详细的说明和代码示例,可帮助您使用该控件。此外,CodeProject上的页面提供了详细的示例,介绍了如何使用
DataGrid
控件执行任何操作。

伙计们,我正在为未来的访问者发布这些技巧。 我没有添加gridview,而是将主机添加到了窗口中,它起了作用

 this.Children.Add(HOST);  

此处已解决:

什么是根网格?我的IDE无法识别它。也许他已经有很多填充DataGridView的代码,不想全部重写。Sheridan,我实际上是在使用DATAGRID本身。但是,我正在动态填充我的列标题(在一个for-each循环中),然后添加行(在另一个for-each循环中)。现在我想使用datagridview的原因是,我在删除datagrid的特定列时遇到问题。你对此有什么建议吗?