ListBox SelectedItem从KVP到ViewModelBase

时间:2011-12-21 09:55:25

标签: wpf data-binding mvvm view dictionary

我有一个列表框绑定到包含我的ViewModel的Dictionary,列表框在Dictionary中显示KeyValuePair的Key。

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

CurrentView是当前在ContentControl中显示的视图。

当ListBox中的选择发生变化时,我得到以下异常:

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]].

它正在尝试将KVP转换为ViewModelBase,我该如何设置它以便将KVP的值设置为CurrentView?

1 个答案:

答案 0 :(得分:0)

在您的情况下,而不是SelectedItem,您需要绑定到SelectedValue并使用SelectedValuePath属性:

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

因为您不希望选择整个列表框项目只是KeyValuePair的Value属性。