簡體   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