【问题标题】:Binding two List<String> to DataGrid将两个 List<String> 绑定到 DataGrid
【发布时间】:2015-01-27 19:30:33
【问题描述】:

我有两个列表,打算在一个 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>

谁能帮帮我?

【问题讨论】:

标签: c# wpf list datagrid


【解决方案1】:

如果你想成对显示时间和温度(分两列),试试这个:

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

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


您尚未将列定义包装在 &lt;DataGrid.Columns&gt;...&lt;/DataGrid.Columns&gt; 中,因此您提供的列被错误地添加到 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>

【讨论】:

  • 你在哪一行得到它?
  • 我从这行得到错误:dtgCsvData.ItemsSource = Time.Zip(Temperature, (t, c) =&gt; new { Time = t, Temperature = c });
  • 呃,我刚刚注意到您的 XAML 中有一个错误。编辑我的答案。
【解决方案2】:

我认为您正在尝试实现以下代码。请检查一下。

<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; }
}

【讨论】:

    猜你喜欢
    • 2013-12-07
    • 1970-01-01
    • 2011-02-21
    • 2017-05-13
    • 1970-01-01
    • 2015-01-02
    • 1970-01-01
    • 1970-01-01
    • 2015-12-14
    相关资源
    最近更新 更多