简体   繁体   English

将 BindingList 绑定到 ListBox 时遇到问题

[英]Trouble binding a BindingList to ListBox

In the app I'm working on, I need to maintain a list of Projects which are currently loaded, and display the names of each one in a ListBox (okay, multiple ListBoxes, but that's neither here nor there).在我正在开发的应用程序中,我需要维护当前加载的项目列表,并在 ListBox 中显示每个项目的名称(好吧,多个 ListBox,但既不存在也不存在)。

class Project
{
    public String Name;

    // Etc. etc...
}

I've got a BindingList object which contains all of the loaded Projects, and am binding it to my ListBox(es).我有一个 BindingList 对象,它包含所有加载的项目,并将它绑定到我的 ListBox(es)。

private BindingList<Project> project_list = new BindingList<Project>();
private ListBox project_listbox;

private void setList()
{
    project_listbox.DisplayMember = "Name";
    project_listbox.ValueMember = "Name";
    project_listbox.DataSource = project_list;
}

However when I do this, all that gets displayed in project_listbox is a set of the class names for the Project.但是,当我这样做时,在project_listbox显示的只是项目的一组类名。 Am I missing something here?我在这里错过了什么吗? Every reference that I could find regarding binding Lists to a ListBox uses a very similar setup.我能找到的关于将 List 绑定到 ListBox 的每个参考都使用非常相似的设置。

You need to make the properties readable :)您需要使属性可读:)

class Project
{
    public string Name {get; private set;}

    // Etc. etc...
}

Now it should work.现在它应该可以工作了。 I just tested it.我刚刚测试了它。

This should work as well: 这也应该有效:

 
 
 
  
  public readonly string Name;
 
 

As I have been pointed out.正如我被指出的那样。 Putting "readonly" doesn't work.放置“只读”不起作用。 I just tested and verified it myself.我只是自己测试和验证过。

As an aside, note that if you want to search on or sort the BindingList, you will need to implement it and add this functionality顺便说一句,请注意,如果您想对 BindingList 进行搜索或排序,则需要实现它并添加此功能

http://msdn.microsoft.com/en-us/library/ms993236.aspx http://msdn.microsoft.com/en-us/library/ms993236.aspx

一个可能的问题是新项目没有插入到 BindingList 而是插入到它的父 List

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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