2012-12-05 101 views
1

我試圖用C#將一些數組綁定到Wpf數據網格中。我能做的只是將一個數組綁定到數據網格中。有誰知道如何將多個數組綁定到數據網格中?我在下面嘗試的代碼不起作用。 datagrid什麼也沒有顯示。將多個數組綁定到WPF數據網格

我Datagrid的代碼片段:

<DataGrid Name="MyDatagrid" Grid.Column="1" AutoGenerateColumns="False"> 
    <DataGrid.Columns> 
     <DataGridTextColumn Header="Date" Width="60" Binding="{Binding Date}"/> 
     <DataGridTextColumn Header="Time" Width="55" Binding="{Binding Time}"/> 
     <DataGridTextColumn Header="No" Width="69" Binding="{Binding No}"/> 
    </DataGrid.Columns> 
</DataGrid> 

C#代碼片段:

string[] Date = {"2-Nov-2012","2-Nov-2012","2-Nov-2012","2-Nov-2012","2-Nov-2012"}; 
string[] Time={"10:30","10:32","10:35","10:42","10:45"}; 
int[] No = { 1, 2, 3, 4, 5 }; 
MyDataGrid.ItemsSource = No; 
MyDataGrid.ItemsSource = Date; 
MyDataGrid.ItemSource = Time; 
+0

是否所有陣列具有相同的長度(這是不正確的代碼段)? – Dennis

+0

對不起,我錯過了時間數組的數據。是的,所有的陣列應該有相同的長度。 – 0070

回答

4

您不能綁定多個陣列相同的數據網格;但是你可以用一個類實現同樣的目的:使用LINQ

public class Row 
{ 
    public string Date { get; set; } 
    public string Time { get; set; } 
    public int No { get; set; } 
} 

填充:

string[] Date = {"2-Nov-2012","2-Nov-2012","2-Nov-2012","2-Nov-2012","2-Nov-2012"}; 
string[] Time={"10:30","10:32","10:35","10:42","10:45"}; 
int[] No = { 1, 2, 3, 4, 5 }; 

Row[] rows = Date.Select((date, index) => new Row { 
    Date = date, 
    Time = Time[index], 
    No = No[index] 
}).ToArray(); 

MyDataGrid.ItemsSource = rows; 
+0

非常感謝! – 0070

+0

@ 0070沒有概率...! – McGarnagle