In WPF Databinding, I understand that you have DataContext
which tells an element what data it is going to bind to and ItemsSource
which "does the binding".
But e.g. in this simple example it doesn't seem that ItemsSource
is doing anything useful since, what else would you want the Element to do to the DataContext
except bind to it?
<ListBox DataContext="{StaticResource customers}"
ItemsSource="{Binding}">
And in more complex examples of ItemsSource
, you have Path and Source which seems to be encroaching on the territory of DataContext
.
ItemsSource="{Binding Path=TheImages, Source={StaticResource ImageFactoryDS}}"
What is the best way to understand these two concepts as to know when and how to apply each of them in various coding scenarios?
DataContext
is just a handy way to pick up a context for bindings for the cases where an explicit source isn't specified. It is inherited, which makes it possible to do this:
<StackPanel DataContext="{StaticResource Data}">
<ListBox ItemsSource="{Binding Customers}"/>
<ListBox ItemsSource="{Binding Orders}"/>
</StackPanel>
Here, Customers
and Orders
are collections on the resource called "Data". In your case, you could have just done this:
<ListBox ItemsSource="{Binding Source={StaticResource customers}}"/>
since no other control needed the context set.