开发者

Binding arbitrary XML to a datagrid

开发者 https://www.devze.com 2023-01-20 19:32 出处:网络
I\'m completely new at silverlight, and trying to do things \"the right way\". Problem is: I have an XML that I need to get from a web server, and I need to display that data in a datagrid.

I'm completely new at silverlight, and trying to do things "the right way".

Problem is: I have an XML that I need to get from a web server, and I need to display that data in a datagrid.

I've searched around and I've managed to get the following:

say my XML looks l开发者_JAVA技巧ike:

<customers>
    <customer>
        <name>A Person</name>
        <address>my address</address>
    </customer>
    <customer>
        <name>A Guy</name>
        <address>my address 2</address>
    </customer>
</customers>

I can retrieve this and populate a POCO such as:

public class Customer
{
    public string Name { get; set; }

    public string Address { get; set; }
}
...
XDocument oDoc = //read from a string asnychronously
var myData = from info in oDoc.Descendants("customer")
    select new Customer
    {
        Name = Convert.ToString(info.Element("name").Value),
        Address = Convert.ToString(info.Element("address").Value
    };
_grid.ItemsSource = myData;

However, if I take this approach, I won't really be using Silverlight's dynamic binding capabilities.

How can I do this in the "Silverlight" way so that when I (or someone else who actually knows silverlight) look at the code a few years down the line, don't hate absolutely hate what I've done.


Take a look at using the XMLSerializer.Deserialize method to de-serialize your XML automatically without having to deal with XDocument. Your class will look like this:

[XmlRoot]
public class Customer
{
    [XmlElement]
    public string Name { get; set; }

    [XmlElement]
    public string Address { get; set; }

}

Once you have the data de-serialized, take a look at MVVM on how to properly bind the data to your views.

0

精彩评论

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