Question

I am binding the ItemsSource property of a DataGrid to a property in my ViewModel. I am then creating an ICollectionView and creating a default view with the DataGrid's item source like so:

_displayItemsView = CollectionViewSource.GetDefaultView(_displayItems);

where _displayItems is a List and _displayItemsView is an ICollectionView.

Now the problem I am having is that I am allowing users to filter the data grid like so:

                        _displayItemsView.Filter = delegate(object item)
                        {
                            DISPLAY_ITEM displayItem = (DISPLAY_ITEM)item;
                            if ((displayItem.RETAIL_ITEM_DPCI.ToString().ToUpper().Contains(value.ToUpper()))
                                      .
                                      .
                                      .

This works most of the time just great, but if the user is currently editing or adding a row in the DataGrid an un-handled exception is thrown by the ICollectionView. How should I go about detecting if either:

  1. The DataGrid is currently being modified or
  2. The ICollectionView is not in a state to be filtered?

Any guidance is appreciated, and I am open to ideas. Thanks!

Was it helpful?

Solution

For your question number 1, the WPF DataGrid has transaction semantics available to you. If the objects in your bound collection implement IEditableObject, your code will get three notifications: begin edit, end edit, and cancel edit. You can track these notifications and implement a bit of housekeeping code to tell whether or not the DataGrid is being modified. Depending upon your design, you will need to set the DataGrid's SelectionUnit/SelectionMode properties to be consistent with the notifications you want.

For your question number 2, when the underlying collection inherits from IList (ObservableCollection for example), you can get a ListCollectionView by casting CollectionViewSource.GetDefaultView.

The ListCollectionView has several properties on it that will give you the information you need...

  • CurrentEditItem and CurrentAddItem will point to their respective objects when those states are active.

  • IsAddingNew will tell you if an add transaction is in progress

  • IsEditingItem will tell you if an edit transaction is in progress

  • IsInUse will tell if there are any current subscribers

Using these properties and the IEditableObject interface will give you all the information needed to avert the exception you have been getting.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top