繁体   English   中英

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

[英]Bind ComboBox to Two Lists in C#

我有两个清单。 第一个是硬编码的,内容永远不会改变。 第二个可以由用户编辑以添加、更改和删除项目:

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

我想将两个列表的内容一个接一个地绑定到 ComboBox 并在用户编辑 UserItems 列表时自动更新。

第一部分我可以通过以下方式轻松解决:

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;

问题是当 UserItems 更改时,没有通知 AllItems 已更改,因此 combobox 的内容保持不变。

然后我添加了一个在 UserItems 更改时生成的事件。 现在我的问题是如何强制 ComboBox 刷新。 执行以下操作:

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

导致 selecteditem 变为 null 并且 selectedindex 变为 -1,然后我必须在我的代码中处理(暂时记住当前项目,之后将其恢复等)。 这一切都变得非常混乱,我相信有一个聪明的方法可以解决这个问题。 在那儿?

谢谢,安迪

更新:我不想仅仅以第三方程序集的形式为此添加更多代码和复杂性,所以我只是继续我的混乱方法。 谢谢。

您需要使用一个集合,该集合将在集合发生更改时通知 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.

暂无
暂无

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

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