Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
874 views
in Technique[技术] by (71.8m points)

wpf - Why are DataContext and ItemsSource not redundant?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...