Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ItemsSource vs DataContext in binding case

My main question is about binding case in the scene that we have multiple sources for a control(a combobox inside a datagrid)(or having both datacontext and itemssource). Then how can we know which source the binding will use? (any syntax to clarify that)

Assuming a datagrid has an itemssource="List of Players" datacontext="Manager" , and has a combobox as a kind of column. We also assume that each player has an Inventory property which is a collection type.

then inside the datagrid.columns:

  1. The current source of each column(for binding) is a Player(this is how i understand it so far). We can only bind to the property of the player not to the property of the datacontext "manager". There is no way to bind to the property of the "Manager". Am i correct?
  2. However, if we move to the combobox columns, then assume i will let combobox's itemssource ='player 's inventory', then the current source for comboboxItem will be each item in the inventory. And if i use the binding, it can only bind to the property of those items. However, sometimes i see the code that we can also bind to the property of the player inside the combobox's property especially Selected Value and SelectedItem. I am a little confused here can you help me?

thank you

like image 982
Tai Avatar asked Aug 19 '10 19:08

Tai


1 Answers

The key control to think about is an ItemsControl (ComboBox inherits from ItemsControl and the DataGrid behaves very similar).

An ItemsControl has ItemsSource property of type IEnumerable. It also has the ItemTemplate property. What it will do is create one copy of it's ItemTemplate for every item in ItemsSource. The DataContext of the ItemTemplate will be each item in the ItemsSource.

In your case of the ComboBox, the DataContext of the DataGrid's column will be your Player object. If you bind the ComboBox's ItemSource to a Player's inventory, then you will get each item in your ComboBox's list.
The thing to note is that the DataContext of the ComboBox itself is unchanged. It is still the Player object. If you specify an ItemTemplate for your ComboBox, that is what will have it's DataContext to the items in a Player's inventory.

like image 177
Stephan Avatar answered Sep 19 '22 19:09

Stephan