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:
- 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?
- 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
The key control to think about is an
ItemsControl(ComboBoxinherits fromItemsControland theDataGridbehaves very similar).An
ItemsControlhasItemsSourceproperty of typeIEnumerable. It also has theItemTemplateproperty. What it will do is create one copy of it’sItemTemplatefor every item inItemsSource. TheDataContextof theItemTemplatewill be each item in theItemsSource.In your case of the
ComboBox, theDataContextof theDataGrid‘s column will be yourPlayerobject. If you bind theComboBox‘sItemSourceto aPlayer‘s inventory, then you will get each item in yourComboBox‘s list.The thing to note is that the
DataContextof theComboBoxitself is unchanged. It is still thePlayerobject. If you specify anItemTemplatefor yourComboBox, that is what will have it’sDataContextto the items in aPlayer‘s inventory.