简体   繁体   中英

How to bind dataset from XML to ItemSource in C# WPF?

I am trying to bind a dataset from XML to an ItemSource and do not get it right.

Here is the .xaml part:

<DataGrid Name="dgLogView" ItemsSource="{Binding}" />

And here is the code behind:

using (XmlLogfileStream logfileStream = new XmlLogfileStream(filename))
{
    // File contents to read
    // <LogInfo><Time>2015-03-14 17:01:43</Time><Message>Logging first time with XML in C#</Message></LogInfo>
    // <LogInfo><Time>2015-03-14 17:02:11</Time><Message>Logging first time with XML in C#</Message></LogInfo>
    // ...

    DataSet ds = new DataSet();
    ds.ReadXml(logfileStream);

    dgLogView.ItemsSource = ds.Tables["LogInfo"].AsEnumerable();
}

A screenshot of the issue:
问题截图

I got the solution by changing my code as follows:

using (XmlLogfileStream logfileStream = new XmlLogfileStream(filename))
{
    DataSet ds = new DataSet();
    DataTable dataTable = new DataTable("LogInfo");
    dataTable.Columns.Add("Time", typeof(string));
    dataTable.Columns.Add("Message", typeof(string));
    ds.Tables.Add(dataTable);

    ds.ReadXml(logfileStream);
    dgLogView.ItemsSource = dataTable.DefaultView;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM