I have a ComboBox with a custom ItemsTemplateSelector. The Items for the control are defined in xaml, like so:
<ComboBox ItemTemplateSelector="{StaticResource CommonListSelectorTemplates}" >
<local:MyItem Heading="First" Text="First Item"/>
<local:MyItem Heading="Second" Text="Second Item"/>
<local:MyItemWithValue Heading="Third" Text="Third Item" Value="{Binding TheValue}" />
</ComboBox>
The third item has a Value property that I wish to bind to the TheValue property on the ComboBox's DataContext. This binding fails with the following error:
"Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=TheValue; DataItem=null; target element is 'MyItemWithValue' (HashCode=49465727); target property is 'Value' (type 'Int32')"
I guess it's becuase the Items collection does not use the ComboBox's DataContext. I have tried different permutations of RelativeSource without success, so my question is: What is the best way to accomplish the binding?
EDIT:
RV1987 answered my question as it was stated. However, what I want is for the binding to be two-way, and neither of the solutions proposed seem to work for this. The trouble may be that I can't get the binding in the proxy to be two-way; the compiler refuses to accept
DataContext="{Binding, Mode=TwoWay}"
ComboboxItems
are not part of visual tree so they are not connected to the data context of the Combobox
. You have to use the proxy binding to refer to the dataContext. For detailed and clean approach please have a look at this link -
Also, look at this (same issue but in this case its datagrid in place of combobox) as suggested by AngelWPF, this was also something new to me -
Bind datagrid column visibility MVVM
Edit- Moreover, you need to set binding mode Two way in your comboboxitem instead of setting it in StaticResource. This should work -
<local:MyItemWithValue Heading="Third" Text="Third Item" Value="{Binding TheValue, Mode=TwoWay}" />