views:

701

answers:

2

Is it possible in WPF to bind a data matrix (data table or an XML file) to a ListView?

Given the following XML dataset:

<data>
  <cols>
    <col name="FirstName" />
    <col name="LastName" />
    <col name="Age" />
  </cols>
  <rows>
    <row>
      <col>Huey</col>
      <col>Freeman</col>
      <col>10</col>
    </row>
    <row>
      <col>Michael</col>
      <col>Caesar</col>
      <col>10</col>
    </row>
    <row>
      <col>Reiley</col>
      <col>Freeman</col>
      <col>8</col>
    </row>
    <row>
      <col>Cindy</col>
      <col null="true" />
      <col>9</col>
    </row>
    <row>
      <col />
      <col>Robert Jebediah Freeman</col>
      <col>70</col>
    </row>
  </rows>
</data>

Is it possible to bind this data to a ListView?

Note that the data columns are not pre-defined. It could of any type and the names vary.

P/S: I am aware of the DataGrid but it is too heavy for usage we just need to display the data.

A: 

You can bind this to a list view, however the columns will not auto-generate. You have to either build your own control that will do this, or find one that someone else has done already.

if you google you will find all kinds of articles with and w/o code.

Muad'Dib
+2  A: 

Hi, You can use the XmlDataProvider for this.

XmlDataProvider data = new XmlDataProvider();

// you can load data from file/http/whatever

data.Source = "... some URL ...";

// *OR* you can go directly against an already existing XmlDocument

// data.Document = someXmlDocumentInstance;

data.XPath = "/books/book"; // specific to your schema obviously

myListView.ItemsSource = data.Data;

You can also setup a binding

Binding myBinding = new Binding();

myBinding.Source = data;

BindingOperations.SetBinding(myListView, ItemsControl.ItemsSourceProperty, myBinding);

HTH

Anand