为什么DataContext和ItemsSource不是冗余的? [英] Why are DataContext and ItemsSource not redundant?
问题描述
DataContext
,它告诉一个元素要绑定什么数据, code> ItemsSource 哪个做绑定。 但是在这个简单的例子中,似乎 ItemsSource
正在做任何有用的工作,因为还有什么要让元素做
< ListBox DataContext ={StaticResource customers}
ItemsSource ={Binding}>
而且在 ItemsSource
,您的路径和源似乎侵犯了 DataContext
的领土。
ItemsSource ={Binding Path = TheImages,Source = {StaticResource ImageFactoryDS}}
了解这两个概念的最佳方法是知道何时以及如何在各种编码场景中应用它们?
DataContext
只是一个方便的方式来为案例绑定提供上下文其中没有指定明确的源。它是继承的,这使得可以这样做:
< StackPanel DataContext ={StaticResource Data}>
< ListBox ItemsSource ={Binding Customers}/>
< ListBox ItemsSource ={Binding Orders}/>
< / StackPanel>
这里,客户
和订单
是名为数据的资源的集合。在您的情况下,您可以这样做:
< ListBox ItemsSource ={Binding Source = {StaticResource customers}} />
因为没有其他控件需要上下文设置。
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.
这篇关于为什么DataContext和ItemsSource不是冗余的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!