我有一个wpf桌面应用程序。
我有一个combox框,它绑定到一个字典对象。
<ComboBox ItemsSource="{Binding MyData}" DisplayMemberPath="Value.Login"
SelectedItem="{Binding MySelectedUser }" SynchronizedWithCurrentItem="True" />
并在我的VM中:
public Dictionary<string,UserRecord> Users
{
get
{
return 'A Dictionary Defined Data'
}
set { _Users = value; RaisePropertyChanged("Users"); }
}
}
public UserRecord SelectedUser
{
get { return _SelectedUser; }
set { _SelectedUser = value;
RaisePropertyChanged(InformedWorkerCommon.Constants.VM_SelectedUser);
}
}
从下拉列表中选择项目时出现的错误是:
System.Windows.Data Error: 23 : Cannot convert '[ADMIN, UI.InformedWorkerViewModel.UserRecord]' from type 'KeyValuePair`2' to type 'UI.InformedWorkerViewModel.UserRecord' for 'en-US' culture with default conversions; consider using Converter property of Binding. NotSupportedException:'System.NotSupportedException: TypeConverter cannot convert from System.Collections.Generic.KeyValuePair`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[UI.InformedWorkerViewModel.UserRecord, UI, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].
at System.ComponentModel.TypeConverter.GetConvertFromException(Object value)
at System.ComponentModel.TypeConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)
at MS.Internal.Data.DefaultValueConverter.ConvertHelper(Object o, Type destinationType, DependencyObject targetElement, CultureInfo culture, Boolean isForward)'
System.Windows.Data Error: 7 : ConvertBack cannot convert value '[ADMIN, UI.InformedWorkerViewModel.UserRecord]' (type 'KeyValuePair`2'). BindingExpression:Path=HeartBeat.CommonData.LogIn.SelectedUser; DataItem='ApplicationViewModel' (HashCode=43160662); target element is 'MetroComboBox' (Name=''); 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],[UI.InformedWorkerViewModel.UserRecord, UI, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].
at MS.Internal.Data.DefaultValueConverter.ConvertHelper(Object o, Type destinationType, DependencyObject targetElement, CultureInfo culture, Boolean isForward)
at MS.Internal.Data.ObjectTargetConverter.ConvertBack(Object o, Type type, Object parameter, CultureInfo culture)
at System.Windows.Data.BindingExpression.ConvertBackHelper(IValueConverter converter, Object value, Type sourceType, Object parameter, CultureInfo culture)
我最初使用的是List,但一切正常,但我需要使用Dictionary集合类型。我只是难过(和谷歌搜索)寻求解决方案。
任何指针/教育我都会很感激。
谢谢!
答案 0 :(得分:1)
你需要告诉你的组合框显示什么以及作为一个值保存什么:
SelectedValuePath="Value" DisplayMemberPath="Key"
现在,由于您使用的是Dictionary<string, UserRecord>
,因此您的组合框将从字典中返回SelectedValue
中的一个项目。这一项是KeyValuePair<string, UserRecord>
,因此无法将其投放到UserRecord
(这就是错误所抱怨的内容)。
答案 1 :(得分:0)