WPF Databinding With A Collection Object

@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.


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" } 
});

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));
    }

}