WPF Databinding With A Collection Object

Posted by Randster on Stack Overflow See other posts from Stack Overflow or by Randster
Published on 2010-05-27T07:13:11Z Indexed on 2010/05/27 7:41 UTC
Read the original article Hit count: 162

Filed under:
|
|

Argh, although I've been googling, I really would appreciate it if someone could break my problem down as all the code examples online are confusing me more than assisting (perhaps it's just late)...

I have a simple class as defined below:

public class Person
{
    int _id;
    string _name;

    public Person()
    { }

    public int ID
    {
        get { return _id; }
        set { _id = value; }
    }

    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }
}

that is stored in a database, and thru a bit more code I put it into an ObservableCollection object to attempt to databind in WPF later on:

 public class People : ObservableCollection<Person>
{
    public People() : base() { }

    public void Add(List<Person> pListOfPeople)
    {
        foreach (Person p in pListOfPeople) this.Add(p);
    }
}

In XAML, I have myself a ListView that I would like to populate a ListViewItem (consisting of a textblock) for each item in the "People" object as it gets updated from the database. I would also like that textblock to bind to the "Name" property of the Person object.

I thought at first that I could do this:

lstPeople.DataContext = objPeople;

where lstPeople is my ListView control in my XAML, but that of course does nothing. I've found TONS of examples online where people through XAML create an object and then bind to it through their XAML; but not one where we bind to an instantiated object and re-draw accordingly.

Could someone please give me a few pointers on:

A) How to bind a ListView control to my instantiated "People" collection object?

B) How might I apply a template to my ListView to format it for the objects in the collection?

Even links to a decent example (not one operating on an object declared in XAML please) would be appreciated.

Thanks for your time.

© Stack Overflow or respective owner

Related posts about wpf

Related posts about databinding