2010-05-18 106 views
1

我试图从文件中获取数据。该文件首先有三行描述该文件的文本,然后在下面有一个标题。我已经设法解压。我遇到的问题是获取标题行下面的数据。标题行下面的数据可能看起来像“1 2 3 4 5 6 7 8 9 abc”。在C#中使用Datacontext填充数据网格WPF

DataGrid dataGrid1 = new DataGrid(); 
masterGrid.Children.Add(dataGrid1); 

using (TextReader tr = new StreamReader(@filename)) 
{ 
    int lineCount = 1; 
    while (tr.Peek() >= 0) 
    { 
     string line = tr.ReadLine(); 
     { 
      string[] data = line.Trim().Split(' '); 

      Dictionary<string, object> sensorData = new Dictionary<string, object>(); 

      for (int i = 0, j = 0; i < data.Length; i++) 
      { 
       //I know that I'm delimiting the data by a space before. 
       //but the data from the text file doesn't necessarily have 
       //just one space between each piece of data 
       //so if I don't do this, spaces will become part of the data. 
       if (String.Compare(data[i]," ") > 0) 
       { 
        sensorData[head[j]] = data[i]; 
        j++; 
       } 
      } 

      sensorDatas.Add(sensorData); 

      sensorData = null; 

     } 
     lineCount++; 
    } 
} 

dataGrid1.DataContext = sensorDatas; 

我不明白为什么这不起作用。如果我更改“dataGrid1.DataContext = sensorDatas;”到“dataGrid1.ItemsSource = sensorDatas;”然后我得到的数据在适当的列中,但我也得到了一些原始视图数据,如:比较器,计数,键,值作为列,我不想要。

任何见解?

回答

3

当您在WPF控件上使用DataContext property时,该控件用于设置控件在填充具有与其关联的绑定的属性时将使用的数据源。

这是一个非常不同于设置ItemsSource property来指示您希望显示在网格中的数据。是的,绑定仍将被使用,但它们以不同的方式用于网格中显示的数据,而不是用于驱动网格配置的数据(这是DataContext的作用)。

相反,您似乎允许网格为您自动生成列。相反,请指出应关闭列的自动生成,然后设置要显示的列。然后,当您设置ItemsSource时,它应该只显示您想要显示的项目。