【发布时间】:2012-01-19 11:32:12
【问题描述】:
问题是,我用这个扩展BindingList
public class RemoveItemEventArgs : EventArgs
{
public Object RemovedItem
{
get { return removedItem; }
}
private Object removedItem;
public RemoveItemEventArgs(object removedItem)
{
this.removedItem = removedItem;
}
}
public class MyBindingList<T> : BindingList<T>
{
public event EventHandler<RemoveItemEventArgs> RemovingItem;
protected virtual void OnRemovingItem(RemoveItemEventArgs args)
{
EventHandler<RemoveItemEventArgs> temp = RemovingItem;
if (temp != null)
{
temp(this, args);
}
}
protected override void RemoveItem(int index)
{
OnRemovingItem(new RemoveItemEventArgs(this[index]));
base.RemoveItem(index);
}
public MyBindingList(IList<T> list)
: base(list)
{
}
public MyBindingList()
{
}
}
我创建了这个扩展类的一个实例,然后尝试使用PropertyGrid 对其进行编辑。当我删除一个项目时,它不会触发删除事件。但是当我使用方法 RemoveAt(...) 编辑实例时,它运行良好。
- 问题的根源是什么?
-
PropertyGrid使用哪种方法删除项目? -
PropertyGrid删除项目时如何捕获删除事件?
例子:
public class Answer
{
public string Name { get; set; }
public int Score { get; set; }
}
public class TestCollection
{
public MyBindingList<Answer> Collection { get; set; }
public TestCollection()
{
Collection = new MyBindingList<Answer>();
}
}
public partial class Form1 : Form
{
private TestCollection _list;
public Form1()
{
InitializeComponent();
}
void ItemRemoved(object sender, RemoveItemEventArgs e)
{
MessageBox.Show(e.RemovedItem.ToString());
}
void ListChanged(object sender, ListChangedEventArgs e)
{
MessageBox.Show(e.ListChangedType.ToString());
}
private void Form1_Load(object sender, EventArgs e)
{
_list = new TestCollection();
_list.Collection.RemovingItem += ItemRemoved;
_list.Collection.ListChanged += ListChanged;
Answer q = new Answer {Name = "Yes", Score = 1};
_list.Collection.Add(q);
q = new Answer { Name = "No", Score = 0 };
_list.Collection.Add(q);
propertyGrid.SelectedObject = _list;
}
}
当我通过 PropertyGrid 编辑集合时,为什么我有新项目的消息,但我没有关于已删除项目的消息?
【问题讨论】:
-
您可能必须显示使用此列表的控件的代码。不知道为什么不使用 BindingList
ListChanged 事件,它有一个 ListChangedEventArgs和一个ListChangedType变量,其中包括一个ItemDeleted枚举。
标签: c# bindinglist