2013-12-12 48 views
0

我正在使用WindowsFormHost,以便能夠在我的WPF應用程序 (以此開始,How to instantiate a Datagridview(in code behind))中使用gridview。WPF控件的鑄造

,並着手爲

public WindowsFormsHost HOST = new WindowsFormsHost(); 

我的GridView控件作爲

System.Windows.Forms.DataGridView gridview = new System.Windows.Forms.DataGridView(); 

(不要忘了引用,請這裏 - http://www.c-sharpcorner.com/uploadfile/mahesh/using-windows-forms-controls-in-wpf/

我有一個DataTable填充它作爲

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' 

爲什麼會這樣? 我的意思是我可以做些什麼來糾正這個問題?

回答

0

夥計我發佈了什麼對我來說是未來的遊客的伎倆。 而不是添加gridview我添加到窗口的主機,它的工作。

this.Children.Add(HOST); 

解決的位置:Using windows forms controls on a WPF page

1

DataGridView是對照WinForms。所以你不能直接添加到WPF控制的孩子。相反如下添加WindowsFormsHost實例:

RootGrid.Children.Add(HOST); 
+0

什麼是RootGrid?我的IDE不識別它。 –

0

這個問題是不是和當前的回答嚴肅???爲什麼您要導入WindowsForms dll,併爲您的WPF應用程序添加CPU密集型WindowsFormsHost元素,以便您可以使用DataGridView控件?你會發現,它的要好得多隻是使用等效WPF控件:DataGrid

你可以找到所有關於DataGrid類通過MSDN上查看DataGrid class頁。此頁面有詳細的說明和代碼示例以幫助您使用該控件。此外,CodeProject上的WPF DataGrid Practical Examples頁面詳細介紹瞭如何處理DataGrid控件可能需要做的任何事情。

+0

也許他已經有很多填充DataGridView的代碼,並且不想將其全部重寫。 –

+0

謝里登,我實際上使用DATAGRID本身。但是,我動態填充我的列標題(在每個循環中),然後添加行(在每個循環的另一個)。現在我想使用datagridview是因爲我有問題要刪除數據網格的特定列。你有什麼建議嗎? –