2012-01-18 33 views
0

的問題是,我使用這個擴展BindingList如何在PropertyGrid刪除此項目時觸發擴展綁定列表項的刪除事件?

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(...)編輯實例時,它運行良好。

  1. 問題的根源是什麼?
  2. PropertyGrid使用哪種方法刪除項目?
  3. 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編輯的最愛?

+0

您可能必須顯示使用此列表的控件的代碼。不知道爲什麼你不會使用BindingList ListChanged事件,該事件有一個ListChangedEventArgs和一個ListChangedType變量,它包含一個ItemDeleted枚舉。 – LarsTech 2012-01-18 16:05:29

回答

1

問題的根源是什麼? PropertyGrid使用哪種方法刪除項目?

問題的根源在於PropertyGrid爲BindingList編輯調用了standard collection editor。此編輯器根本不在集合項上使用Remove()方法,但對編輯後存在於列表中的每個項目僅使用IList.Clear()方法和IList.Add()方法(您可以將CollectionEditor.SetItems()方法傳遞給更詳細的反射器)。