【问题标题】:c# binding IDictionary with Listbox时间:2018-08-10 标签:c#bindingIDictionary与Listbox
【发布时间】:2023-03-11 11:10:01
【问题描述】:

我是 Windows 窗体和学习的新手。 我有一个简单的代码,其中包含一个填充了 listbox1 的表单。我试图通过将其绑定到 IDictionary 实例来填充它。

static IDictionary<string, string> Bind_Data = new Dictionary<string, string>();

    Binding myBinding = new Binding("DataSource", Bind_Data, "Key");   

    listBox1.DataBindings.Add(myBinding);

运行此代码时出现以下错误。

错误:System.Reflection.TargetInvocationException:属性访问器 对象上的“键” 'System.Collections.Generic.Dictionary`2[[System.String, mscorlib, 版本=4.0.0.0,文化=中性, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, 版本=4.0.0.0,文化=中性,PublicKeyToken=b77a5c561934e089]]' 抛出以下异常:'对象与目标类型不匹配。' ---> System.Reflection.TargetException:对象与目标类型不匹配。在 System.Reflection.RuntimeMethodInfo.CheckConsistency(对象目标)

如果有人能帮助我理解这个错误,我真的很感激。

我可以使用

listBox1.DataSource=new Binding(Bind_Data, null);
listBox1.ValueMemeber="Key";
listBox1.DisplayMember="Value";

但我想使用绑定

【问题讨论】:

    标签: c# visual-studio


    【解决方案1】:

    查看该构造函数的 MSDN 文档:https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.binding.-ctor?view=netframework-4.7.2#System_Windows_Forms_Binding__ctor_System_String_System_Object_System_String_

    数据源参数只能是某些对象 - Dictionary 类型没有实现 IList,我怀疑这是您收到上述异常的原因。

    如果您的基础类型必须是字典,您可能希望将其包装在实现 IList 的自定义类中,以便获得所需的绑定,否则只需使用上面的第二种样式

    【讨论】:

    • 感谢您的回复。我没有必要使用字典。但是,我正在尝试弄清楚如何使用 Binding,因为我所做的任何事情都会引发此异常。
    猜你喜欢
    • 2017-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-18
    • 1970-01-01
    • 1970-01-01
    • 2019-04-16
    相关资源
    最近更新 更多