Skip to content

Instantly share code, notes, and snippets.

@olohmann
Created September 14, 2009 19:39
Show Gist options
  • Save olohmann/186876 to your computer and use it in GitHub Desktop.
Save olohmann/186876 to your computer and use it in GitHub Desktop.
public class DragDropFriendlyListBoxItem : ListBoxItem
{
private List<object> previousSelection = new List<object>();
private List<object> currentSelection = new List<object>();
private bool capturedSelectionOnMouseDown;
/// <summary>
/// Finds the parent DragDropFriendly list box.
/// </summary>
/// <returns>The parent <c>DragDropFriendlyListBox</c>.</returns>
private DragDropFriendlyListBox FindParentDragDropFriendlyListBox()
{
Visual visual = this;
while (visual != null && !(visual is DragDropFriendlyListBox))
{
visual = (Visual)VisualTreeHelper.GetParent(visual);
}
return visual as DragDropFriendlyListBox;
}
/// <summary>
/// Called when the user presses the left mouse button over the <see cref="T:System.Windows.Controls.ListBoxItem"/>.
/// </summary>
/// <param name="e">The event data.</param>
protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
{
capturedSelectionOnMouseDown = false;
if (this.IsSelected)
{
previousSelection.Clear();
currentSelection.Clear();
DragDropFriendlyListBox lb = FindParentDragDropFriendlyListBox();
previousSelection.AddRange(lb.SelectedItems.Cast<object>());
base.OnMouseLeftButtonDown(e);
currentSelection.AddRange(lb.SelectedItems.Cast<object>());
lb.UnselectAll();
previousSelection.ForEach(item => lb.SelectedItems.Add(item));
capturedSelectionOnMouseDown = true;
}
else
{
base.OnMouseLeftButtonDown(e);
}
}
/// <summary>
/// Raises the <see cref="E:PreviewMouseLeftButtonUp"/> event.
/// </summary>
/// <param name="e">The <see cref="MouseButtonEventArgs"/> instance containing the event data.</param>
protected override void OnPreviewMouseLeftButtonUp(MouseButtonEventArgs e)
{
// Apply the new selection if required.
if (capturedSelectionOnMouseDown)
{
DragDropFriendlyListBox lb = FindParentDragDropFriendlyListBox();
lb.UnselectAll();
currentSelection.ForEach(item => lb.SelectedItems.Add(item));
}
// Clean up to store no references.
currentSelection.Clear();
previousSelection.Clear();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment