![](/img/trans.png)
[英]Combobox with composite collection not updating with changes to observablecollection
[英]ComboBox items not updating when underlying ObservableCollection changes
我有一個ComboBox
和一個ObservableCollection
設置為該ComboBox
DataSource
。
當我以編程方式從可觀察的集合中添加/刪除項目時, ComboBox
沒有任何變化。
我究竟做錯了什么?
第2部分:嘗試將BindingSource
用作ObservableCollection
的代理。 從ObservableCollection
編程方式添加/刪除項目時,不會觸發類似ListChanged
或類似事件的事件。
底層集合更改時,如何使ComboBox
自動更新其列表?
public Form1()
{
InitializeComponent();
comboBox1.DataSource = new ObservableCollection<MyItem>(
new []
{
new MyItem() { Name = "AAA"},
new MyItem() { Name = "BBB"},
});
}
private void Button3_Click(object sender, EventArgs e)
{
// Nothing changes in the ComboBox when I add a new item to ObservableCollection
((ObservableCollection<MyItem>)(comboBox1.DataSource))
.Add(new MyItem() { Name = Guid.NewGuid().ToString()});
}
}
public class MyItem
{
public string Name { get; set; }
}
它有助於將列表包裝在BindingList<T>
。 這里是一些測試代碼:
public partial class Form1 : Form
{
private readonly List<string> _coll = new List<string> { "aaaaa", "bbbbb", "ccccc" };
private readonly BindingList<string> _blist;
private readonly Random _rand = new Random();
private const string Templ = "mcvnoqei4yutladfffvtymoiaro875b247ytmlarkfhsdmptiuo58y1toye";
public Form1()
{
InitializeComponent();
_blist = new BindingList<string>(_coll);
comboBox1.DataSource = _blist;
}
private void AddButton_Click(object sender, EventArgs e)
{
int i = _rand.Next(Templ.Length - 5);
string s = Templ.Substring(i, 5);
_blist.Add(s);
}
}
請注意,您必須對BindingList
進行更改(添加,刪除等)。 BindingSource
以相同的方式工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.