2010-12-16 96 views
3

我試圖讓DataGrid顯示一個object[][]的內容。這將是隻讀的,所以我不在乎通知的變化或類似的東西。將ItemSource設置爲object[][]只是在網格中顯示Array的屬性,而使用List<List<object>>代替它會相同,這顯然是無益的。在DataGrid中顯示二維數組

每個1d數組中的列數可以是任意的;我只想爲每行中的每個數組元素創建一個未命名的列。我怎樣才能做到這一點?

+1

從5點10K,恭喜:) – 2010-12-16 13:51:54

+1

@Meleak:謝謝:) – thecoop 2010-12-16 14:49:14

回答

1

請參閱我的回答this question。這也將啓用值的編輯。由於您只是想顯示它們,所以如果使用DataGrid不是必需條件,那麼使用Jobi Joy的答案可能會更容易。

從這個問題得到一個簡短的答案。你需要一個參考類

public class Ref<T> 
{ 
    private readonly Func<T> getter; 
    private readonly Action<T> setter; 
    public Ref(Func<T> getter, Action<T> setter) 
    { 
     this.getter = getter; 
     this.setter = setter; 
    } 
    public T Value { get { return getter(); } set { setter(value); } } 
} 

和輔助類從二維數組

public class BindingHelper 
{ 
    public DataView GetBindable2DViewFromIList<T>(IList list2d) 
    { 
     DataTable dataTable = new DataTable(); 
     for (int i = 0; i < ((IList)list2d[0]).Count; i++) 
     { 
      dataTable.Columns.Add(i.ToString(), typeof(Ref<T>)); 
     } 
     for (int i = 0; i < list2d.Count; i++) 
     { 
      DataRow dataRow = dataTable.NewRow(); 
      dataTable.Rows.Add(dataRow); 
     } 
     DataView dataView = new DataView(dataTable); 
     for (int i = 0; i < list2d.Count; i++) 
     { 
      for (int j = 0; j < ((IList)list2d[i]).Count; j++) 
      { 
       int a = i; 
       int b = j; 
       Ref<T> refT = new Ref<T>(() => (list2d[a] as IList<T>)[b], z => { (list2d[a] as IList<T>)[b] = z; });      
       dataView[i][j] = refT; 
      } 
     } 
     return dataView; 
    } 
} 

得到動態列後,您可以使用的ItemsSource這樣

<DataGrid Name="dataGrid" 
      RowHeaderWidth="0" 
      ColumnHeaderHeight="0" 
      AutoGenerateColumns="True" 
      AutoGeneratingColumn="dataGrid_AutoGeneratingColumn"/> 

dataGrid.ItemsSource = BindingHelper.GetBindable2DViewFromIList<object>(m_2DArray); 

private void dataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e) 
{ 
    DataGridTextColumn column = e.Column as DataGridTextColumn; 
    Binding binding = column.Binding as Binding; 
    binding.Path = new PropertyPath(binding.Path.Path + ".Value"); 
} 
+0

我最終在DataTable中使用'Rows.Add(rowArray)'創建行,並使用'AsDataView'擴展方法獲取DataView。 – thecoop 2010-12-16 14:14:23