GridViewExtensions.BindableSelection problem

Feb 6, 2013 at 10:30 AM
Hi,
I'm using the GridViewExtensions.BindableSelection in a SemanticZoom to keep track of the selected items. In addition I want to use the ObservableCollection (that is binded in the GridViewExtensions.BindableSelection) in my ViewModel to set the selected items for the UI, but if I add an Item to the OC I get the "Cannot change ObservableCollection during a CollectionChanged event." exception.

Call Stack:
   at System.Collections.ObjectModel.ObservableCollection`1.CheckReentrancy()
   at System.Collections.ObjectModel.ObservableCollection`1.InsertItem(Int32 index, T item)
   at System.Collections.ObjectModel.Collection`1.Add(T item)
   at CallSite.Target(Closure , CallSite , Object , Object )
   at System.Dynamic.UpdateDelegates.UpdateAndExecuteVoid2[T0,T1](CallSite site, T0 arg0, T1 arg1)
   at CallSite.Target(Closure , CallSite , Object , Object )
   at WinRTXamlToolkit.Controls.Extensions.GridViewBindableSelectionHandler.OnGridViewSelectionChanged(Object sender, SelectionChangedEventArgs e)
   at System.Runtime.InteropServices.WindowsRuntime.IVector`1.Append(T value)
   at System.Runtime.InteropServices.WindowsRuntime.VectorToCollectionAdapter.Add[T](T item)
   at WinRTXamlToolkit.Controls.Extensions.GridViewBindableSelectionHandler.OnBoundSelectionChanged(Object sender, NotifyCollectionChangedEventArgs e)
   at System.Collections.Specialized.NotifyCollectionChangedEventHandler.Invoke(Object sender, NotifyCollectionChangedEventArgs e)
   at System.Collections.ObjectModel.ObservableCollection`1.OnCollectionChanged(NotifyCollectionChangedEventArgs e)
   at System.Collections.ObjectModel.ObservableCollection`1.InsertItem(Int32 index, T item)
   at System.Collections.ObjectModel.Collection`1.Add(T item)
   at MyClass.AddItemToTheSelectedItems(MyObject myObject)
It looks like the extension registers that a new item has been selected and hence it tries to add this item to the OC that is bounded to GridViewExtensions.BindableSelection. This action is not possible since the OC can't be changed during a CollectionChanged event.

One possible solution would be to check if an item is already in the OC:
private void OnGridViewSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            foreach ( dynamic item in e.RemovedItems )
            {
                if ( _boundSelection.Contains(item) )
                {
                    _boundSelection.Remove(item);
                }
            }
            foreach ( dynamic item in e.AddedItems )
            {
                if ( !_boundSelection.Contains(item) )
                {
                    _boundSelection.Add(item);
                }
            }
        }
Am I using GridViewExtensions.BindableSelection the wrong way or is this an issue?
Thanks in advance for your Help.
Darius
Feb 12, 2013 at 3:19 PM