【问题标题】:Binding more than one array to a WPF datagrid将多个数组绑定到 WPF 数据网格
【发布时间】:2012-12-05 05:25:13
【问题描述】:

我尝试使用 C# 将一些数组绑定到 Wpf 数据网格中。我能做的只是将一个数组绑定到数据网格中。有谁知道如何将多个数组绑定到数据网格中?我在下面尝试的代码不起作用。数据网格什么也不显示。

我的Datagrid代码sn-p:

<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#代码sn-p:

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;

【问题讨论】:

  • 所有数组的长度都相同吗(您的代码 sn-p 不是这样)?
  • 对不起,我错过了时间数组的数据。是的,所有的数组都应该有相同的长度。

标签: c# wpf datagrid


【解决方案1】:

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

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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-31
    • 2017-05-14
    • 1970-01-01
    • 2012-06-05
    • 2011-05-28
    • 2012-11-21
    相关资源
    最近更新 更多