2012-01-18 4 views
0

の問題は、私はこれは私がこの拡張クラスのインスタンスを作成し、その後、私はPropertyGridを使用して、それを編集しようPropertyGridでこのアイテムを削除すると、拡張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() 
    { 
    } 
} 

BindingListを拡張使用することです。アイテムを削除すると、削除イベントは発生しません。しかし、メソッド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

おそらく、このリストを使用しているコントロールのコードを表示する必要があります。 The BindingList ListChangedイベントには、 'ListChangedEventArgs'と' ListChangedType'変数があり、 'ItemDeleted'列挙型を含んでいます。 – LarsTech

答えて

1

問題の原因を教えてください。 PropertyGridはアイテムを削除するためにどのメソッドを使用しますか?

問題の原因は、PropertyGridがBindingList編集のためにstandard collection editorを呼び出したことです。このエディタでは、コレクションアイテムに対してRemove()メソッドは使用されませんが、IList.Clear()メソッドとIList.Add()メソッドのみがリストの編集後に存在します(CollectionEditor.SetItems()メソッドを詳細についてはリフレクタを参照してください)。

関連する問題