ItemsSource和DataContext之间

ItemsSource和DataContext之间

本文介绍了ItemsSource和DataContext之间与ListBox有关的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不太想知道ItemsSource和DataContext之间的区别。有人可以解释它并提供示例支持吗?

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.

我正在阅读文档,它说我可以使用DataContext进行绑定,但是我在上面扔了一个ObservableCollection,但没有显示任何内容在列表中。如果我将相同的集合放在ItemsSource上,它将正常工作。

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.

推荐答案

控件(包括ListBox)什么都不做的值为 DataContext 。其目的是为数据绑定提供上下文。

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.

让我们假设您有一个 ListBox myList和 MyData myData。 MyData 类型具有类型为 ObservableCollection< Person> 的属性 People,进而具有人员类型具有字符串属性 Forename和 Surname。

Lets assume you have a ListBox "myList" and a MyData "myData". The MyData type has a property "People" of type ObservableCollection<Person> and in turn the Person type has the string properties "Forename" and "Surname".

以下所有内容均等效:-

All of the following are equivalent:-

 myList.ItemsSource = myData.People;

 myList.DataContext = myData;
 myList.SetBinding(ItemsControl.ItemsSourceProperty, new Binding("People"));

 myList.DataContext = myData.People;
 myList.SetBinding(ItemsControl.ItemsSourceProperty, new Binding());

通常,尽管绑定是在Xaml中配置的,并且LayoutRoot的DataContext被分配了数据对象:-

Typically though bindings are configured in Xaml and the DataContext of the LayoutRoot is assigned the data object:-

 LayoutRoot.DataContext = myData;

您可能具有以下Xaml:-

you might have the following Xaml:-

 <Grid x:Name="LayoutRoot">
   <ListBox x:Name="myList" ItemsSource="{Binding People}">
     <ListBox.ItemTemplate>
       <DataTemplate>
         <StackPanel Orientation="Horizontal">
           <TextBlock Text="{Binding Forename}" Margin="2" />
           <TextBlock Text="{Binding Surname}" Margin="2" />
         </StackPanel>
       </DataTemplate>
     </ListBox.ItemTemplate>
   </ListBox>
 </Grid>

您会在此处注意到以下几点。完全未分配 myList的 DataContext 。在这种情况下,对控件的祖先树进行遍历,直到找到一个确实为 DataContext 属性分配了值的祖先为止。

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 the DataContext property.

还为每个 Person 实例动态生成的每个 ListBoxItem 都具有 Person 实例被分配为其 DataContext ,这就是Forename和Surname绑定如何工作的方式。

Also each ListBoxItem dynamically generated for each Person instance has that Person instance assigned as its DataContext which is how the Forename and Surname bindings manage to work.

这篇关于ItemsSource和DataContext之间与ListBox有关的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 18:46