/// <summary> /// Returns data as a SelectionCollection. /// </summary> /// <param name="data">The data object.</param> /// <returns>A selection collection.</returns> internal static SelectionCollection ToSelectionCollection(object data) { //------------------------ // The purpose of this method is to wrap data into a "Selection" class // (unless it is already a Selection), and then put the Selection // into a SelectionCollection (unless it is already a SelectionCollection). //------------------------ if (data == null) { return(new SelectionCollection()); } SelectionCollection selectionCollection = data as SelectionCollection; if (selectionCollection == null) { selectionCollection = new SelectionCollection(); Selection selection = data as Selection; if (selection == null) { selection = new Selection(data); } selectionCollection.Add(selection); } return(selectionCollection); }
/// <summary> /// Adds all selected items when drag operation begins. /// </summary> /// <param name="eventArgs">Information about the event.</param> protected override void OnItemDragStarting(ItemDragEventArgs eventArgs) { SelectionCollection selectionCollection = new SelectionCollection(); // If panel is virtualized there is no way of knowing the precise // index of each selected item. Panel itemsHost = this.ListBox.GetItemsHost(); if (itemsHost is VirtualizingPanel) { foreach (object item in this.ListBox.SelectedItems) { selectionCollection.Add(new Selection(item)); } // Adding the item dragged even if it isn't selected SelectionCollection defaultSelectionCollection = SelectionCollection.ToSelectionCollection(eventArgs.Data); if (defaultSelectionCollection.Count == 1 && !selectionCollection.Any(selection => object.Equals(selection.Item, defaultSelectionCollection[0].Item))) { selectionCollection.Add(defaultSelectionCollection[0]); } } else { for (int cnt = 0; cnt < this.ListBox.Items.Count; cnt++) { ListBoxItem listBoxItem = this.ListBox.ItemContainerGenerator.ContainerFromIndex(cnt) as ListBoxItem; if (listBoxItem.IsSelected) { selectionCollection.Add(new Selection(cnt, this.ListBox.Items[cnt])); } } // Adding the item dragged even if it isn't selected SelectionCollection defaultSelectionCollection = GetSelectionCollection(eventArgs.Data); if (defaultSelectionCollection.Count == 1) { if (selectionCollection.All(selection => selection.Index != defaultSelectionCollection[0].Index)) { selectionCollection.Add(defaultSelectionCollection[0]); } } } eventArgs.Data = selectionCollection; CardPanel cardPanel = new CardPanel(); IEnumerable <UIElement> itemContainers = selectionCollection.SelectedItems .Select(item => this.ListBox.ItemContainerGenerator.ContainerFromItem(item)) .Where(item => item != null) .OfType <UIElement>(); foreach (ListBoxItem row in itemContainers) { cardPanel.Children.Add(new Image { Source = new WriteableBitmap(row, new TranslateTransform()) }); } eventArgs.DragDecoratorContent = cardPanel; eventArgs.Handled = true; base.OnItemDragStarting(eventArgs); }