的BindingList我的同班同学填充使用它的属性组合框?我的、它的、组合、同班

2023-09-07 02:45:08 作者:我一出门,风就抱住了我

我有我的类的BindingList,我想用它的属性,因此,当我的列表更改组合框会随之发生改变来填充组合框。

I have a BindingList with my class where I would like to populate a ComboBox using a property of it so when my list changes the ComboBox would change as well.

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>();

在我的窗体加载我给它分配给组合框:

On my form load I assign it to the ComboBox:

myComboBox.DataSource = accessList;

我想填充盒访问或使用ACCESSID的价值和访问作为印刷的名称。

I want to populate the box with Access or with the AccessId as value and Access as the printed name.

问题是,它会打印清单的唯一的最后一个项目的组合框我究竟做错了什么?

Problem is that it will print only the last item of the list to the combobox what am I doing wrong ?

推荐答案

使用的DisplayMember 来指定要使用的字段在组合框显示。 让 accesslist中 只读来保证你永远不会重新创建列表的新实例。如果你不让它只读,这可能会引入一个微妙的错误,如果你不重新分配数据源时你recereate accesslist中

Use DisplayMember to specify what field to use for display in the ComboBox. Make accessList readonly to guarantee that you never recreate a new instance of the list. If you don't make it readonly, this may introduce a subtle bug, if you don't reassign DataSource whenever you recereate accessList.

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]。访问=Test3的),并查看更改UI中体现出来,你需要实施 INotifyPropertyChanged的

If you need to be able to change items properties in accessList (like accessList[0].Access = "Test3") and see the changes reflected in UI, you need to implement 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;
}