I have a listbox bound to an Dictionary that holds my ViewModels, the listbox displays the Key of the KeyValuePair in the Dictionary.
<ListBox Style="{StaticResource MenuListBox}" x:Name="MenuItems" ItemsSource="{Binding Path=Screens}" ItemContainerStyle="{StaticResource MenuListBoxItem}" SelectedItem="{Binding Path=CurrentView}" />
CurrentView is the current View that is getting displayed in a ContentControl.
When the selection changes in the ListBox I get this exception:
System.Windows.Data Error: 7 : ConvertBack cannot convert value '[Top 100, ModBox.ViewModel.Top100ViewModel]' (type 'KeyValuePair`2'). BindingExpression:Path=CurrentView; DataItem='MainViewModel' (HashCode=18169760); target element is 'ListBox' (Name='MenuItems'); target property is 'SelectedItem' (type 'Object') NotSupportedException:'System.NotSupportedException: TypeConverter cannot convert from System.Collections.Generic.KeyValuePair`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[GalaSoft.MvvmLight.ViewModelBase, GalaSoft.MvvmLight.WPF4, Version=0.0.0.0, Culture=neutral, PublicKeyToken=63eb5c012e0b3c1c]].
It is trying to convert a KVP to a ViewModelBase, how can I make it so it sets the Value of the KVP to the CurrentView?
In your case instead of the
SelectedItemyou need to bind to SelectedValue and use the SelectedValuePath property:Because you don’t want to whole list box item selected just the Value property of the KeyValuePair.