0

I have a class, name it People that implements INotifyPropertyChanged and has two properties: Name and Surname.

public IList<People> myCollection;
myCollection = new ObservableCollection<People>();
myCollection.add(new People("Jerry", "Jerry");
myCollection.add(new People("Tom", "Tom");

in XAML i have a listbox named 'ListOfNames' I can do:

ListOfNames.ItemsSource = myCollection;

And everything works just fine. My question is, how can I assign myCollection as ItemsSource through XAML?

With a single object like:

People myPerson = new People("Tom", "Tom");

<Window.Resources>
   <local:People x:Key="myPerson" />
</Window.Resources>

<label Content="{Binding source={StaticResource myPerson}}" />

Binding works properly. Yet, if I try with list:

<Window.Resources>
   <local:People x:Key="myCollection" />
</Window.Resources>

<ListBox ItemsSource="{Binding source={StaticResource myCollection}}" />

It does not display anything. Clearly, I've misunderstood something and doing it wrong. I assume it expects an object 'People' and getting a list of objects is confusing it, meaning, list should be referenced differently. How should it be done please.

  • 2
    Possible duplicate of [How can I bind an ItemsControl.ItemsSource with a property in XAML?](https://stackoverflow.com/questions/16694327/how-can-i-bind-an-itemscontrol-itemssource-with-a-property-in-xaml) – dymanoid May 03 '18 at 11:38
  • Try ObservableCollection instead – Nekeniehl May 03 '18 at 11:40

1 Answers1

0

You cannot bind to a field, you must bind to a property.

public ObservableCollection<> MyCollection
{
    get { return _myCollection; }
    set { _myCollection = value; }
}

<ListBox ItemsSource="{Binding Path=MyCollection}" />

This will work provided you've set your DataSource correctly at the window level.

slugster
  • 49,403
  • 14
  • 95
  • 145