I have a ComboBox with the DataContext defined at application start to the appropriate ViewModel. I want to grab items from a XML file but have user selections bind to the ViewModel, and ultimately the model.
XAML:
<ComboBox x:Name="cbConnection"
ItemsSource="{Binding Source={StaticResource XmlConnectionList}, XPath=//ComboItem}"
DisplayMemberPath="Key"
SelectedValuePath="Value"
SelectionChanged="{Binding Path=DataContext.cbConnection_SelectionChanged}"
/>
but I am getting the following exception at runtime:
{"Unable to cast object of type 'System.Reflection.RuntimeEventInfo' to type 'System.Reflection.MethodInfo'."}
We know the ViewModel is appropriately set as the DataContext of the View’s Window. What am I doing wrong?
You are using;
Which is actually an event.
You should bind a Public Property (possibly implementing INotifyPropertyChanged) in your ViewModel to the SelectedItem Property to manage changes tn the Selection.
Assuming that your window has the DataContext, rather than the combobox itself…
SelectedItem Binding Version:
So your XAML would be something like;
And in your ViewModel;
Text Binding Version:
Of course, if all your interested in is the Text Value of what they’ve chosen, you could in theory just bind the ComboBox Text Property to a Public String Property in your ViewModel;
Your XAML would then be;
And your ViewModel;
SelectedValue Binding Version:
If you are displaying the Key, but want the Value from the Key/Value Pair, then you should bind to the SelectedValue;
XAML;
ViewModel;
Note the extra @ symbols.
As I mentioned above, this assumes that your Window has the DataContext set here. If not, then remove the “DataContext.”‘s from the Bindings above!
I assume you’re seeing items listed in your ComboBox currently?
Hope this helps!