我想构建一个对象列表。列表中的对象将引发一个事件,该对象应从列表中删除。我该如何建立这种机制?那种机制逻辑吗?
public class object()
{
public event EventHandler listEmpty;
List<string> name;
...
public void Delete(string n)
{
name.Remove(n);
...
if(name.isEmpty())
//raise an event hier..
}
}
public class MyClass
{
public List<object> ObjList = new List<object>();
public Remove(string x)
{
ObjList[5].Delete(x);
}
private void OnListIsEmpty(object sender, EventArgs e)
{
ObjList.RemoveAt(5);
}
public MyClass()
{
// how to subscribe this event??
}
}
答案 0 :(得分:0)
我认为ObservableCollection
和INotifyPropertyChanged
符合您的要求。
请参阅以下示例。
public class Model : INotifyPropertyChanged
{
public Model(string val)
{
Value = val;
}
string Value { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
}
static void Main(string[] args)
{
ObservableCollection<Model> collection = new ObservableCollection<Model>();
collection.Add(new Model("item1"));
collection.Add(new Model("item2"));
collection.Add(new Model("item3"));
collection.CollectionChanged += (sender, e) =>
{
if (e.Action == NotifyCollectionChangedAction.Remove)
{
var removedItems = e.OldItems; // put a breakpoint here to observe
}
};
collection.RemoveAt(1);
Console.ReadLine();
}