ListBox 方面的 ItemsSource 和 DataContext 之间的差异
我不太明白 ItemsSource 和 DataContext 之间的区别。有人可以解释它并用例子支持它吗?我什么时候会使用其中之一。
我正在阅读文档,它说我可以使用 DataContext 进行绑定,但我向它抛出一个 ObservableCollection,但列表中没有显示任何内容。如果我在 ItemsSource 中抛出相同的集合,它就可以正常工作。
I am not quite grokking the difference between ItemsSource and DataContext. Can someone explain it and back it up with examples? When would I use one or the other.
I am reading the docs and it says that I can bind using DataContext, but I throw an ObservableCollection at it and nothing shows up in the list. If I throw the same collection at the ItemsSource, it works fine.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
控件(包括 ListBox)根本不对
DataContext
的值执行任何操作。其目的是为数据绑定提供上下文。假设您有一个
ListBox
“myList”和一个MyData
“myData”。MyData
类型具有ObservableCollection
类型的属性“People”,而Person
类型具有字符串属性“Forename”和“姓”。以下所有内容都是等效的:-
或
或
通常,虽然绑定是在 Xaml 中配置的,并且 LayoutRoot 的 DataContext 已分配数据对象:-
您可能具有以下 Xaml:-
您将在此处注意到一些事项。 “myList”的
DataContext
根本没有分配。在这种情况下,将遍历控件的祖先树,直到找到确实具有分配给DataContext
属性的值的祖先。此外,为每个
Person
实例动态生成的每个ListBoxItem
都将该Person
实例分配为其DataContext
,这就是 Forename 的方式和姓氏绑定设法工作。Controls (including the ListBox) don't do anything with the value of
DataContext
at all. Its purpose is to provide a context for data bindings.Lets assume you have a
ListBox
"myList" and aMyData
"myData". TheMyData
type has a property "People" of typeObservableCollection<Person>
and in turn thePerson
type has the string properties "Forename" and "Surname".All of the following are equivalent:-
or
or
Typically though bindings are configured in Xaml and the DataContext of the LayoutRoot is assigned the data object:-
you might have the following Xaml:-
You'll note a couple of things here. The
DataContext
of "myList" is not assigned at all. In this case the control's ancestor tree is walked until an ancestor is found that does have a value assigned to theDataContext
property.Also each
ListBoxItem
dynamically generated for eachPerson
instance has thatPerson
instance assigned as itsDataContext
which is how the Forename and Surname bindings manage to work.