/// <summary> /// DataGrid.SelectionChanged handler to update the source list given the SelectionChangedEventArgs /// </summary> private static void UpdateSourceListOnDataGridSelectionChanged(object sender, SelectionChangedEventArgs selectionChangedArgs) { ListView dataGrid = sender as ListView; IList selectedItemsSource = ListViewMultipleSelection.GetSelectedItemsSource(dataGrid) as IList; Debug.Assert(selectedItemsSource != null, "SelectedItemsSource must be of type IList"); // If the source list initiated the changes then don't pass the DataGrid's changes back down to the source list if (!ListViewMultipleSelection.selectedItemsSources[selectedItemsSource.GetHashCode()].InitiatedSelectionChange) { ListViewMultipleSelection.SetInitiatedSelectionChange(dataGrid, true); foreach (object removedItem in selectionChangedArgs.RemovedItems) { selectedItemsSource.Remove(removedItem); } foreach (object addedItem in selectionChangedArgs.AddedItems) { if (IsGenericList(selectedItemsSource.GetType(), addedItem.GetType())) { selectedItemsSource.Add(addedItem); } } ListViewMultipleSelection.SetInitiatedSelectionChange(dataGrid, false); } }
/// <summary> /// INotifyCollectionChanged.CollectionChanged handler for updating DataGrid.SelectedItems when the source list changes /// </summary> private static void UpdateDataGridsOnSourceCollectionChanged(object source, NotifyCollectionChangedEventArgs collectionChangedArgs) { DataGridsAndInitiatedSelectionChange sourceListInfo = ListViewMultipleSelection.selectedItemsSources[source.GetHashCode()]; // For each DataGrid that is bound to this list, is alive, and did not initate selection changes, update its selection sourceListInfo.InitiatedSelectionChange = true; IList sourceList = source as IList; Debug.Assert(sourceList != null, "SelectedItemsSource must be of type IList"); ListView dataGrid = null; foreach (WeakReference dataGridReference in sourceListInfo.BoundDataGridReferences) { if (dataGridReference.IsAlive && !ListViewMultipleSelection.GetInitiatedSelectionChange(dataGridReference.Target as ListView)) { dataGrid = dataGridReference.Target as ListView; UpdateDataGrid(dataGrid, sourceList, collectionChangedArgs); } } sourceListInfo.InitiatedSelectionChange = false; }