2010-10-20 80 views
1

我環顧四周,但所有可找到的示例都使用了XAML,這使得解決方案過於靜態。這是我想要做的:如何動態地將XML綁定到C#中的WPF數據網格

我想從運行時指定的XML文件填充DataGrid的列,行和屬性。 DataGrid的屬性沒有任何可修復的地方; XML將其驅動到最後的細節(因此我看到的XAML示例爲什麼不夠用)。

XML文件的細節是開放的,所以任何佈局都可以,但是作爲一個例子:

<data> 
    <row Column="Col 1" Value="100" /> 
    <row Column="Col 2" Value ="200" /> 
</data> 

會產生指定的列&值分別與所述值(「西1 2列的網格「,100)&(」列2「,200)分別針對行1 & 2。

再一次,我完全不同的XML沒有問題,所以我會採取什麼行之有效的。

類似這樣的東西似乎非常有用,因爲它允許在各種域中創建通用數據查看組件。 XML將爲傳輸結構化數據提供便利的通用格式,DataGrid將提供豐富的觀看體驗。

回答

0

您可以將XML序列化爲集合並綁定該集合。

您可以從您的XML創建數據表並將其綁定到數據網格。

只要你有主從格式沒關係你把它的結構數據。

,如果你做出這樣的XML,

呈現行中的數據和有列值。

2

謝謝大家花時間閱讀或回覆我的請求。我想出瞭如何做到這一點,幷包括下面的代碼片段:

using System.Xml.Linq; // Required for XElement... 
using System.Collections; // Required for Hashtable 

private void InitGridFromXML(string xmlPath) 
{ 
    var data = XElement.Load(xmlPath); 

    // Set Grid data to row nodes (NOTE: grid = DataGrid member) 
    var elements = data.Elements("row"); 
    grid.ItemsSource = elements; 

    // Create grid columns from node attributes. A hashtable ensures 
    // only one column per attribute since this iterates through all 
    // attributes in all nodes. This way, the grid can handle nodes with 
    // mutually different attribute sets. 
    var cols = new Hashtable(); 
    foreach (var attr in elements.Attributes()) 
    { 
     var col = attr.Name.LocalName; 

     // Only add col if it wasn't added before 
     if (!cols.Contains(col)) 
     { 
      // Mark col as added 
      cols[col] = true; 

      // Add a column with the title of the attribute and bind to its 
      // value 
      grid.Columns.Add(new DataGridTextColumn 
      { 
       Header = col, 
       Binding = new Binding("Attribute[" + col + "].Value") 
      }); 
     } 
    } 
} 
+0

我喜歡這個,感謝發佈它。我調整了屬性,但效果很好。 – 2015-12-18 13:32:18

相關問題