<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); } }
}
Thats my code. And i got this DataGrid:
But Here is extra row and column. How to show only my grid 5x5 without empty row?
I suggest you to check the return values of GetLength(0) and GetLength(1) to make sure that they do what you expect them to. In addition, I always had one additional row (to create a new row on the fly) when I used Data Grids.
Update: The additional row disappears when you set IsReadOnly to "True" (like I said, it is made for on the fly edits) and the additional column is not a real column, it is the space of the row header, shown on the right. It disappears when setting HeadersVisibility to "All" or "Row".