3

我的班级有一个 BindingList,我想使用它的属性填充 ComboBox,因此当我的列表更改时,ComboBox 也会更改。

public class UserAccess
{
    public override string ToString()
    {
        return Access;
    }
    public int AccessId { get; set; }
    public string Access { get; set; }
    public List<string> Command = new List<string>();

    public bool HasCommand(string cmd)
    {
        return this.Command.Any(x => x == cmd);
    }
}

public BindingList<UserAccess> accessList = new BindingList<UserAccess>();

在我的表单加载中,我将其分配给 ComboBox:

myComboBox.DataSource = accessList;

我想用 Access 或 AccessId 作为值和 Access 作为打印名称填充该框。

问题是它只会将列表的最后一项打印到组合框我做错了什么?

4

1 回答 1

4

用于DisplayMember指定用于在 中显示的字段ComboBox
确保accessList readonly您永远不会重新创建列表的新实例。如果你不成功,这可能会引入一个微妙的错误,如果你在重新分配时readonly不重新分配。DataSourceaccessList

private readonly BindingList<UserAccess> accessList = new BindingList<UserAccess>();

public Form1()
{
    InitializeComponent();

    comboBox1.ValueMember = "AccessId";
    comboBox1.DisplayMember = "Access";
    comboBox1.DataSource = accessList;
}

private void button1_Click(object sender, EventArgs e)
{
    accessList.Add(new UserAccess { AccessId = 1, Access = "Test1" });
    accessList.Add(new UserAccess { AccessId = 2, Access = "Test2" });
}

如果您需要能够更改 accessList 中的项目属性(如accessList[0].Access = "Test3")并查看 UI 中反映的更改,则需要实现INotifyPropertyChanged.

例如:

public class UserAccess : INotifyPropertyChanged
{
    public int AccessId { get; set; }

    private string access;

    public string Access
    {
        get
        {
            return access;
        }

        set
        {
            access = value;
            RaisePropertyChanged("Access");
        }
    }

    private void RaisePropertyChanged(string propertyName)
    {
        var temp = PropertyChanged;
        if (temp != null)
            temp(this, new PropertyChangedEventArgs(propertyName));
    }

    public event PropertyChangedEventHandler PropertyChanged;
}
于 2011-05-28T20:55:50.583 回答