将两个List <string>绑定到DataGrid </string>

时间:2015-01-27 19:30:33

标签: c# wpf list datagrid

我有两个列表,它意味着在一个DataGrid中显示。

此代码生成InvalidOperationException:

这是我的属性部分:

public List<String> Temperature;
public List<String> Time;

列表如何填充数据

Temperature = new List<string>(reader.GetTemperature());
Time = new List<string>(reader.GetTime());

我如何在C#

中绑定到DataGrid
dtgCsvData.ItemsSource = Temperature;
dtgCsvData.ItemsSource = Time;

XAML:

<DataGrid x:Name="dtgCsvData" HorizontalAlignment="Left" Margin="10,187,0,0" VerticalAlignment="Top" Height="200" Width="250" AutoGenerateColumns="False">
     <DataGridTextColumn Binding="{Binding Temperature}" Header="Temperature" IsReadOnly="True"/>
     <DataGridTextColumn Binding="{Binding Time}" Header="Time" IsReadOnly="True" />
</DataGrid>

有人能帮助我吗?

2 个答案:

答案 0 :(得分:2)

如果要成对显示时间和温度(两列),请尝试以下操作:

dtgCsvData.ItemsSource = Time.Zip(Temperature, (t,c) => 
    new {Time = t, Temperature = c});

使用Zip,您将两个序列配对,并使用该对创建一个新的匿名类型对象。然后,DataGrid应该能够使用您在xaml中定义的绑定将每对显示为一行。


您尚未在<DataGrid.Columns>...</DataGrid.Columns>中包装列定义,因此您提供的列错误地会添加到DataGrid.Items。由于您无法同时设置DataGrid.ItemsDataGrid.ItemsSource,因此您获得了InvalidOperationException。解决它:

<DataGrid x:Name="dtgCsvData" HorizontalAlignment="Left" Margin="10,187,0,0" VerticalAlignment="Top" Height="200" Width="250" AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding Temperature}" Header="Temperature" IsReadOnly="True"/>
        <DataGridTextColumn Binding="{Binding Time}" Header="Time" IsReadOnly="True" />
    </DataGrid.Columns>
</DataGrid>

答案 1 :(得分:1)

我认为您正在尝试实现类似下面的代码。请检查一下。

<DataGrid x:Name="dtgCsvData" HorizontalAlignment="Left" VerticalAlignment="Top" Height="200" Width="250" AutoGenerateColumns="False">
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding Temperature}" Header="Temperature" IsReadOnly="True"/>
            <DataGridTextColumn Binding="{Binding Time}" Header="Time" IsReadOnly="True" />
        </DataGrid.Columns>            
    </DataGrid>
public partial class MainWindow : Window
{        
    public MainWindow()
    {
        InitializeComponent();
        List<MyClass> lst = new List<MyClass>();
        lst.Add(new MyClass() { Temperature = "60 F", Time = "2:30 PM" });
        lst.Add(new MyClass() { Temperature = "62 F", Time = "2:35 PM" });
        dtgCsvData.ItemsSource = lst;
    }        
}

class MyClass
{
    public string Temperature { get; set; }
    public string Time { get; set; }
}