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

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

问题描述

在 WPF 数据绑定中,我知道您有 DataContext 它告诉元素它将绑定到什么数据和 ItemsSource 进行绑定".

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".

但是例如在这个简单的示例中,ItemsSource 似乎没有做任何有用的事情,因为您还希望 Element 对 DataContext 除了绑定到它?

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}">

在更复杂的 ItemsSource 示例中,您有 Path 和 Source,它们似乎侵占了 DataContext.

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}}"

了解这两个概念以了解何时以及如何在各种编码场景中应用它们的最佳方法是什么?

推荐答案

DataContext 只是一种在未指定显式源的情况下为绑定选择上下文的便捷方式.它是继承的,这使得这样做成为可能:

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>

此处,CustomersOrders 是名为Data"的资源上的集合.就您而言,您可以这样做:

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天全站免登陆