我编写了一个显示项目列表的控件(在本例中只是字符串)。我给了开发人员一个项目列表,他可以在其中添加和删除项目(参见下面的代码)。我希望有一种方法可以在添加新项目时得到通知。因此,作为一种 react ,控件可以更新。
private List<string> items = new List<string>();
public List<string> Items
{ get { return items; } }
我该怎么做? List<...>
没有事件。我能做什么?
看看 BindingList<T>
和 ObservableCollection<T>
. This answer解释两者之间的区别。
除了绑定(bind)之外,您还可以像这样订阅更改事件:
BindingList<T>.<a href="http://msdn.microsoft.com/en-us/library/ms132742(v=vs.110).aspx" rel="noreferrer noopener nofollow">ListChanged</a>
:
items.ListChanged += (sender, e) => {
// handle the change notification
};
ObservableCollection<T>.<a href="http://msdn.microsoft.com/en-us/library/ms653375(v=vs.110).aspx" rel="noreferrer noopener nofollow">CollectionChanged</a>
:
items.CollectionChanged += (sender, e) => {
// handle the change notification
};