Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Databinding With A Collection Object

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.

like image 683
Randster Avatar asked May 27 '10 07:05

Randster


3 Answers

Indeed 'Anderson Imes' response is correct (upvote), although I have two remarks:

First, if you only need to display one property of an object, I think it's easier and cleaner to use ListBox instead of ListView, because the code for binding the property will be reduced to

<ListBox x:Name="lstPeople" DisplayMemberPath="Name" />

Second, if you are using WPF and Binding, make sure your objects implement INotifyPropertyChanged, so that changes are always synchronized between UI and the objects.

public class Person : INotifyPropertyChanged
{
    int _id;
    string _name;

    public Person()
    { }

    public int ID
    {
        get { return _id; }
        set { 
             _id = value; 
             RaisePropertyChanged("ID");
            }
    }

    public string Name
    {
        get { return _name; }
        set { 
             _name = value;  
             RaisePropertyChanged("Name");
            }
    }

    pivate void RaisePropertyChanged(string propName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propName));
    }

}
like image 165
RoelF Avatar answered Nov 14 '22 05:11

RoelF


You were so close.

lstPeople.ItemsSource = objPeople; // :)

The only other thing you need is how to apply a view for each item in your collection. No problem. I won't use a ListView... I'll just use an ItemsControl because it's a bit simpler.

<ItemsControl x:Name="lstPeople">
    <ItemsControl.ItemTemplate>
         <DataTemplate>
              <TextBlock Text="{Binding Name}" />
         </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

That's pretty much it. The strategy is the same for a Listview, but you need to provide just a tad more XAML to provide column headers and stuff. I'm not 100% sure you need this at the moment, so I left it out.

Edit: Here's an extension method for "AddRange" that will do what you are trying to do by subclassing ObservableCollection. Little easier... especially if you end up with a lot of collection types (you will)

public static void AddRange<T>(this ObservableCollection<T> collection, IEnumerable<T> items)
{
     foreach(var item in items)
     {
          collection.Add(item);
     }
}

Then you can just do:

ObservableCollection<Person> peeps = new ObservableCollection<Person>();
peeps.AddRange(new List<Person>
{ 
     new Person() { Name = "Greg" }, 
     new Person() { Name = "Joe" } 
});
like image 29
Anderson Imes Avatar answered Nov 14 '22 03:11

Anderson Imes


@Anderson beat me by seconds, my answer was very similar.

One thing i will add though: there is no need to define a new type of collection that inherits from ObservableCollection, instead you can just do this:

ObservableCollection<Person> myPeopleCollection = new ObservableCollection<Person>();

the only time you want to extend it is if you are going to be doing something different or fancy with it, which you don't appear to be doing.

like image 1
slugster Avatar answered Nov 14 '22 05:11

slugster