为什么DataContext和ItemsSource不是冗余的? [英] Why are DataContext and ItemsSource not redundant?

查看:99
本文介绍了为什么DataContext和ItemsSource不是冗余的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在WPF数据绑定中,我明白你有 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆