如何应对二维数据显示和编辑
How to cope with bidimensional data display AND edit
我必须在数据网格中显示双 X、Y 偏移量。
我的想法是(用 excel 和 photoshop 完成):
允许用户更改偏移值。在行和列上也印有数字。
目前偏移量结构是:
public Point[,] pointMatrix;
但是当我将其关联到数据网格时出现此错误:
所以也许二维数组不是正确的类型。
关于如何操作的任何提示?
不幸的是,您无法将 DataGrid
的 ItemSource
设置为二维数组,您需要将其绑定到 List<List<Point>>
或 DataTable
,使用 DataTable
对您来说更容易,因为它不需要太多更改,添加以下转换器方法,将 2D 数组转换为 DataTable:
private DataView ConvertFromMatrixToDataTable(Point[,] matrix)
{
var myDataTable = new DataTable();
for (int i = 0; i < matrix.GetLength(0); i++)
{
myDataTable.Columns.Add(i.ToString());
}
for (int j = 0; j < matrix.GetLength(1); j++)
{
var row = myDataTable.NewRow();
for (int i = 0; i < matrix.GetLength(0); i++)
{
row[i] = matrix[i, j];
}
myDataTable.Rows.Add(row);
}
return myDataTable.DefaultView;
}
然后用它来影响DataGrid
的ItemSource
:
dtgNests.ItemsSource = ConvertFromMatrixToDataTable(pointMatrix);
我必须在数据网格中显示双 X、Y 偏移量。 我的想法是(用 excel 和 photoshop 完成):
允许用户更改偏移值。在行和列上也印有数字。
目前偏移量结构是:
public Point[,] pointMatrix;
但是当我将其关联到数据网格时出现此错误:
所以也许二维数组不是正确的类型。 关于如何操作的任何提示?
不幸的是,您无法将 DataGrid
的 ItemSource
设置为二维数组,您需要将其绑定到 List<List<Point>>
或 DataTable
,使用 DataTable
对您来说更容易,因为它不需要太多更改,添加以下转换器方法,将 2D 数组转换为 DataTable:
private DataView ConvertFromMatrixToDataTable(Point[,] matrix)
{
var myDataTable = new DataTable();
for (int i = 0; i < matrix.GetLength(0); i++)
{
myDataTable.Columns.Add(i.ToString());
}
for (int j = 0; j < matrix.GetLength(1); j++)
{
var row = myDataTable.NewRow();
for (int i = 0; i < matrix.GetLength(0); i++)
{
row[i] = matrix[i, j];
}
myDataTable.Rows.Add(row);
}
return myDataTable.DefaultView;
}
然后用它来影响DataGrid
的ItemSource
:
dtgNests.ItemsSource = ConvertFromMatrixToDataTable(pointMatrix);