WPF Lover
WPF Lover

Reputation: 309

Select ListBoxItem on MouseUp WPF

I have a ListBox with multiple selection. And I am doing drag and drop operation in it. I used Ctrl+A to select all items. But once I have click an item to start drag, items got deselected. Is there any way to select/deselect listboxitem on mouse up.

Upvotes: 2

Views: 3049

Answers (1)

AndrewS
AndrewS

Reputation: 6094

The ListBoxItem overrides its OnMouseLeftButtonDown and invokes a method on the containing ListBox that handles the selection. So if you want to mouse down on a selected listbox item and initiate a drag you will need to start that before this happens on the ListBoxItem. So you might try handling the PreviewMouseLeftButtonDown on the ListBox and checking the e.OriginalSource. If that is a ListBoxItem or an element within the listbox item (you'll need to walk up the visual tree) then you can initiate your drag operation. E.g.

private void OnPreviewLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    var source = e.OriginalSource as DependencyObject;

    while (source is ContentElement)
        source = LogicalTreeHelper.GetParent(source);

    while (source != null && !(source is ListBoxItem))
        source = VisualTreeHelper.GetParent(source);

    var lbi = source as ListBoxItem;

    if (lbi != null && lbi.IsSelected)
    {
        var lb = ItemsControl.ItemsControlFromItemContainer(lbi);
        e.Handled = true;
        DragDrop.DoDragDrop(....);
    }

}

Upvotes: 4

Related Questions