2011-02-16 97 views
1
<DataGrid Name="grid" 
       HorizontalAlignment="Left" 
       VerticalAlignment="Top" 
       IsReadOnly="False" 
       HeadersVisibility="None" 
       AutoGenerateColumns="True" 
       AutoGeneratingColumn="c_dataGrid_AutoGeneratingColumn"> 

public static DataView GetBindable2DArray<T>(this T[,] array) 
     { 
      DataTable dataTable = new DataTable(); 
      for (int i = 0; i < array.GetLength(1); i++) 
      { 
       dataTable.Columns.Add(i.ToString(), typeof(Ref<T>)); 
      } 
      for (int i = 0; i < array.GetLength(0); i++) 
      { 
       DataRow dataRow = dataTable.NewRow(); 
       dataTable.Rows.Add(dataRow); 
      } 
      DataView dataView = new DataView(dataTable); 
      for (int i = 0; i < array.GetLength(0); i++) 
      { 
       for (int j = 0; j < array.GetLength(1); j++) 
       { 
        int a = i; 
        int b = j; 
        Ref<T> refT = new Ref<T>(() => array[a, b], z => { array[a, b] = z; }); 
        dataView[i][j] = refT; 
       } 
      } 
      return dataView; 
     } 

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); } } 
    } 

這就是我的代碼。而我得到這個數據網格:

enter image description here

DataGrid額外的列和行

但這裏是多餘的行和列。如何只顯示我的網格5x5沒有空行?

+0

你會得到什麼** GetLength()**,你肯定要處理變量! – V4Vendetta 2011-02-16 06:26:43

回答

1

我建議您檢查GetLength(0)和GetLength(1)的返回值,以確保它們按照您的期望操作。另外,當我使用數據網格時,我總是有另外一行(用於創建一個新的行)。

更新: 當您將IsReadOnly設置爲「True」(如我所說,它是用於即時編輯)並且附加列不是實際列時,附加行會消失,它是行的空間標題,如右圖所示。將HeadersVisibility設置爲「全部」或「行」時消失。