views:

1100

answers:

1

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?

+6  A: 

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.

HTH, Kent

Kent Boogaart
Thanks, the second part of your answer is the link I was missing between DataContext and Source. So you can think of it like this: <ListView ItemsSource="{Binding DataContext={StaticResource customers}}"> (in fact, I wonder why WPF doesn't just use that syntax)
Edward Tanguay
@Edward: Perhaps, but there are other kinds of sources, such as RelativeSource and ElementName. Check out the API docs for the Binding class.
Kent Boogaart