开发者

Converting String[] to Expando for binding DataGrid in WPF

开发者 https://www.devze.com 2023-02-03 09:21 出处:网络
I am wor开发者_如何学Pythonking on a system that parses files and imports them into a WPF DataGrid. The files are split into a collection string[] and passed back to me to display in the UI.

I am wor开发者_如何学Pythonking on a system that parses files and imports them into a WPF DataGrid. The files are split into a collection string[] and passed back to me to display in the UI.

What is the easiest way to convert this collection of string[] into something that can be bound to a WPF (.NET4) DataGrid?

Aside: I'd like to use Expando .....


Unfortunately dynamic objects like Expando do not work yet with WPF4 in my testing. However, there are other tried and true methods that are available.

For a collection of String[], you can use a DataTable to give you dynamic columns:

var rawData = new string[][]
{
    new string[] { "R1F1", "R1F2", },
    new string[] { "R2F1", "R2F2", },
};
var fieldNames = Enumerable.Range(1, rawData[0].Length).Select(field => "Field" + field);
var table = new DataTable();
table.Columns.AddRange(fieldNames.Select(fieldName => new DataColumn(fieldName)).ToArray());
foreach (var record in rawData)
{
    DataRow row = table.NewRow();
    for (int i = 0; i < record.Length; i++)
    {
        row[i] = record[i];
    }
    table.Rows.Add(row);
}
DataContext = table;

together with XAML like this:

<Grid>
    <DataGrid ItemsSource="{Binding}"/>
</Grid>

results in:

Converting String[] to Expando for binding DataGrid in WPF

0

精彩评论

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