[英]ComboBox items not updating when underlying ObservableCollection changes
I have a ComboBox
and an ObservableCollection
set as DataSource
for that ComboBox
. 我有一个ComboBox
和一个ObservableCollection
设置为该ComboBox
DataSource
。
When I programmatically add/remove items from the observable collection, nothing changes in the ComboBox
. 当我以编程方式从可观察的集合中添加/删除项目时, ComboBox
没有任何变化。
What am I doing wrong? 我究竟做错了什么?
Part 2: tried to put a BindingSource
as a proxy for ObservableCollection
. 第2部分:尝试将BindingSource
用作ObservableCollection
的代理。 When programmatically added/removed items from ObservableCollection
, no event like ListChanged
or similar fired. 从ObservableCollection
编程方式添加/删除项目时,不会触发类似ListChanged
或类似事件的事件。
How can I make a ComboBox
automatically update its list when underlying collection changes? 底层集合更改时,如何使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; }
}
It helps to wrap a list in a BindingList<T>
. 它有助于将列表包装在BindingList<T>
。 Here a little test code: 这里是一些测试代码:
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);
}
}
Note that you have to make the changes (Add, Remove etc.) to the BindingList
. 请注意,您必须对BindingList
进行更改(添加,删除等)。 The BindingSource
works the same way. BindingSource
以相同的方式工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.