Difference between ItemsSource and DataContext as pertains to ListBox

后端 未结 1 1703
傲寒
傲寒 2020-12-08 03:04

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.

1条回答
  •  有刺的猬
    2020-12-08 03:36

    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 a MyData "myData". The MyData type has a property "People" of type ObservableCollection and in turn the Person type has the string properties "Forename" and "Surname".

    All of the following are equivalent:-

     myList.ItemsSource = myData.People;
    

    or

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

    or

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

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

     LayoutRoot.DataContext = myData;
    

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

    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.

    0 讨论(0)
提交回复
热议问题