2

我想到了如果我在自定義集合上實現了INotifyCollectionChanged,DataGridView將訂閱CollectionChanged事件。DataGridView和INotifyCollectionChanged

我的集合實現IListSource和INotifyCollectionChanged,並有一個內部BindingList。我訂閱來自BindingList的ListChanged事件並調用我的OnCollectionChanged方法,然後引發CollectionChanged事件。

也許有更好的方法來完成上述,我會很高興聽到它。不過,我目前主要關注的是獲得的DataGridView更新這種方法被調用後:

public void Sort(List<SortField> sortFields) 
    { 
     if(sortFields == null || sortFields.Count == 0) return; 

     IOrderedEnumerable<T> res; 

     if (sortFields[0].Ascending) 
      res = _items.OrderBy(o => o[sortFields[0].Name]); 
     else 
      res = _items.OrderByDescending(o => o[sortFields[0].Name]); 

     for (int x = 1; x < sortFields.Count; x++) 
      if (sortFields[x].Ascending) 
       res = res.ThenBy(o => o[sortFields[x].Name]); 
      else 
       res = res.ThenByDescending(o => o[sortFields[x].Name]); 

     Items = new BindingList<T>(res.ToList()); 
     OnListChanged(this, new ListChangedEventArgs(ListChangedType.Reset, null)); 
    } 

上午我在我的信念誤以爲在DataGridView訂閱到CollectionChanged事件還是我做別的事情了?

回答

1

我假設您正在使用ObservableCollection<T>類作爲您的自定義集合。 DataGridView不知道INotifyCollectionChanged。它旨在用於WPF綁定,而不是在WinForms中使用。

請參閱this有關更多信息的SO問題。

+0

啊,好的。不,我沒有使用ObservableCollection,但是我曾經在WPF中使用過一些,所以聽起來好像我必須剛剛混合起來才認爲DGV會支持INotifyCollectionChanged。謝謝。 – BVernon