2011-12-21 61 views
0

我有一個列表框綁定到一個詞典,包含我的ViewModels,列表框顯示KeyValuePair在詞典中的鍵。ListBox SelectedItem從KVP到ViewModelBase

<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 ?

回答

0

在你的情況,而不是你需要綁定到SelectedValue和使用SelectedValuePath屬性SelectedItem

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

因爲你不想選擇只是KeyValuePair的Value屬性全列表框項目。

+1

我對這個簡單的東西打破了我的想法!? * -facepalm- *,哦,好吧。謝謝! – MrZunz 2011-12-21 10:14:47

相關問題