开发者

Populate datagrid using Datacontext in C# WPF

I'm trying to get data from file. The file first has three lines of text that describes the file, then there is a header for the data below. I've managed to extract that. What I'm having problems is getting the data below the header line. The data below the header line can look like "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开发者_如何学Go'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;

I can't figure out why this doens't work. If I change "dataGrid1.DataContext = sensorDatas;" to "dataGrid1.ItemsSource = sensorDatas;" then I get the data in the proper columns, but I also get some Raw View data such as: Comparer, Count, Keys, Values as columns, which I don't want.

Any insight?


When you use the DataContext property on a control in WPF, that is used to set the data source that the control will use when populating properties which have bindings associated with them.

This is a very different thing than setting the ItemsSource property to indicate the data you wish to show in the grid. Yes, bindings will still be used, but they are used in a different way for the data that is shown in the grid, not the data that is used to drive the configuration of the grid itself (which is what DataContext does).

Rather, it seems that you are allowing the grid to auto-generate the columns for you. Instead, indicate that the auto-generation of the columns should be shut off, and then set the columns you wish to display. Then, when you set the ItemsSource, it should show only the items you wish to show.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜