将多个数组绑定到WPF数据网格

时间:2012-12-05 05:25:13

标签: c# wpf datagrid

我尝试使用C#将一些数组绑定到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;

1 个答案:

答案 0 :(得分:4)

您无法将多个数组绑定到同一个数据网格;但你可以用一个类来达到同样的目的:

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

使用Linq填充:

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;