我正在尝试从文件中获取数据。该文件首先有三行描述该文件的文本,然后是下面数据的标题。我已经设法提取它。我遇到的问题是获取标题行下方的数据。标题行下方的数据可能类似于“1 2 3 4 5 6 7 8 9 abc”。
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;”然后我在正确的列中获取数据,但我也得到一些原始 View 数据,例如:比较器、计数、键、值作为列,这是我不想要的。
有什么见解吗?
最佳答案
当您使用 DataContext
property时在 WPF 中的控件上,用于设置控件在填充与其关联的绑定(bind)的属性时将使用的数据源。
这与设置 ItemsSource
property 非常不同。指示您希望在网格中显示的数据。是的,仍然会使用绑定(bind),但它们以不同的方式用于网格中显示的数据,而不是用于驱动网格本身配置的数据(这就是 DataContext
所做的)。
相反,您似乎允许网格为您自动生成列。相反,指示应关闭列的自动生成,然后设置您希望显示的列。然后,当您设置 ItemsSource
,它应该只显示您想要显示的项目。
关于c# - 在 C# WPF 中使用 Datacontext 填充数据网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2859978/