简体   繁体   中英

ListBox SelectedItem from KVP to ViewModelBase

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 SelectedItem you need to bind to SelectedValue and use the SelectedValuePath property:

<ListBox Style="{StaticResource MenuListBox}" x:Name="MenuItems" 
    ItemsSource="{Binding Path=Screens}" 
    ItemContainerStyle="{StaticResource MenuListBoxItem}" 
    SelectedValue="{Binding Path=CurrentView}"
    SelectedValuePath="Value" 
    />

Because you don't want to whole list box item selected just the Value property of the KeyValuePair.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM