简体   繁体   English

将 ComboBox 绑定到 C# 中的两个列表

[英]Bind ComboBox to Two Lists in C#

I have two lists.我有两个清单。 The first one is hard-coded and the contents never change.第一个是硬编码的,内容永远不会改变。 The second can be edited by the user to add, change and remove items:第二个可以由用户编辑以添加、更改和删除项目:

public List<Item> DefaultItems = new List<Item>();
public BindingList<Item> UserItems = new BindingList<Item>();
...
MyTable.DataSource = UserItems;

I would like to bind the contents of both lists, one after the other, to a ComboBox and have it update automatically when the user edits the UserItems list.我想将两个列表的内容一个接一个地绑定到 ComboBox 并在用户编辑 UserItems 列表时自动更新。

The first part I can easily solve with something like:第一部分我可以通过以下方式轻松解决:

public List<Items> AllItems
{
    get
    {
        List<Item> Items = new List<Item>();
        foreach (Item I in DefaultItems) Items.Add(I);
        foreach (Item I in UserItems) Items.Add(I);
        return Items;
    }
}
...
MyComboBox.DataSource = AllItems;

The problem is that when UserItems changes there is no notification that AllItems has changed so the contents of the combobox remain the same.问题是当 UserItems 更改时,没有通知 AllItems 已更改,因此 combobox 的内容保持不变。

I then added an event that is generated when UserItems changes.然后我添加了一个在 UserItems 更改时生成的事件。 Now my problem is how to force the ComboBox to refresh.现在我的问题是如何强制 ComboBox 刷新。 Doing the following:执行以下操作:

MyComboBox.DataSource = null;
MyComboBox.DataSource = AllItems;

results in the selecteditem becoming null and the selectedindex becoming -1, which I then have to handle in my code (temporarily remember the current item, restore it afterwards, etc.).导致 selecteditem 变为 null 并且 selectedindex 变为 -1,然后我必须在我的代码中处理(暂时记住当前项目,之后将其恢复等)。 It's all becoming very messy and I'm sure there is a clever way of solving this.这一切都变得非常混乱,我相信有一个聪明的方法可以解决这个问题。 Is there?在那儿?

thanks, Andy谢谢,安迪

UPDATE: I didn't want to add yet more code and complexity just for this in the form of a third party assembly, so I just continued with my messy approach.更新:我不想仅仅以第三方程序集的形式为此添加更多代码和复杂性,所以我只是继续我的混乱方法。 Thanks.谢谢。

You need to use a collection that will notify the UI when the collection has been changed.您需要使用一个集合,该集合将在集合发生更改时通知 UI。

You can either use the .NET provided BindingList class or, if you want to try something different, you could download the BindingListView class that will wrap your existing collections and provide the UI with the notification it needs. You can either use the .NET provided BindingList class or, if you want to try something different, you could download the BindingListView class that will wrap your existing collections and provide the UI with the notification it needs.

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

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