I am not quite grokking the difference between ItemsSource and DataContext. Can someone explain it and back it up with examples? When would I use one or the other.
I am reading the docs and it says that I can bind using DataContext, but I throw an ObservableCollection at it and nothing shows up in the list. If I throw the same collection at the ItemsSource, it works fine.
Controls (including the ListBox) don’t do anything with the value of
DataContextat all. Its purpose is to provide a context for data bindings.Lets assume you have a
ListBox“myList” and aMyData“myData”. TheMyDatatype has a property “People” of typeObservableCollection<Person>and in turn thePersontype has the string properties “Forename” and “Surname”.All of the following are equivalent:-
or
or
Typically though bindings are configured in Xaml and the DataContext of the LayoutRoot is assigned the data object:-
you might have the following Xaml:-
You’ll note a couple of things here. The
DataContextof “myList” is not assigned at all. In this case the control’s ancestor tree is walked until an ancestor is found that does have a value assigned to theDataContextproperty.Also each
ListBoxItemdynamically generated for eachPersoninstance has thatPersoninstance assigned as itsDataContextwhich is how the Forename and Surname bindings manage to work.