2013-06-04 58 views
1

我的應用程序中有一個數據網格,我想將多維數組的布爾項綁定到網格。如何將不同值的多維數組綁定到數據網格

如何將下列項目綁定到datagrid ItemsSource?

爲如

 bool[,] matrix = new bool[10, 22]; 

     matrix[0, 1] = true; 
     matrix[0, 2] = false; 
     matrix[0, 3] = true; 
     matrix[1, 1] = false; 
     matrix[1, 3] = true; 

什麼,我已經盡力了,我看到一個空的DataGrid

public MatrixPage() 
    { 
     InitializeComponent(); 
     bool[,] matrix = new bool[5, 5]; 

     matrix[0, 1] = true; 
     matrix[0, 2] = false;    
     matrix[0, 3] = true; 

     var datsource = (from i in Enumerable.Range(0, matrix.GetLength(0)) 
         select new clsdatasource(matrix[0, 1], matrix[0, 2], matrix[0, 3])).ToList(); 

     Matrix_datagrid.ItemsSource = datsource; 
    } 

    public class clsdatasource 
    { 
     public bool str1 { get; set; } 
     public bool str2 { get; set; } 
     public bool str3 { get; set; } 

     public clsdatasource(bool s1, bool s2, bool s3) 
     { 
      this.str1 = s1; 
      this.str2 = s2; 
      this.str3 = s3; 
     } 
     } 
    } 

回答

1

您在LINQ表達式有錯誤,你應該使用i變量,而不是0

var datsource = (from i in Enumerable.Range(0, matrix.GetLength(0)) 
        select new clsdatasource(matrix[i, 1], matrix[i, 2], matrix[i, 3])).ToList(); 

在xaml我只有以下代碼和everythin g工作得很好。

<DataGrid Name="Matrix_datagrid" /> 

實施例:

bool[,] matrix = new bool[5, 5]; 

matrix[0, 1] = true; 
matrix[0, 2] = false; 
matrix[0, 3] = true; 
matrix[1, 1] = true; 
matrix[2, 2] = true; 

結果:

enter image description here

+0

下面的代碼矩陣[I,0],[I,1],[I,2]僅填充第一行..如果我想填充第二行和其他行如此...,條件是什麼???我必須使用另一種說法嗎? – user1221765

+0

@ user1221765帶變量'i'的代碼完全從'matrix'移動數據。所以如果你想填充第二行和其他行,你應該首先在'matrix'中填充數據。再次檢查我的答案。 – kmatyaszek

相關問題