Drag and drop list items?

How to select items in the list if you start dragging from one item to the end of the drag?

+3
source share
1 answer

I found this approach in the msdn question, but I can’t find it again, so I can’t link it .. Anyway, this works pretty well, only the problem is drag and drop and scroll at the same time, then it can skip a few items. I created a special control library called MultiSelectLibrary, which you can use as follows

Add a link to MultiSelectLibrary, which can be downloaded from here (Source here )
Add a namespace and MultiSelectListBox with SelectionMode = "Extended", and it should work.

xmlns:mslb="clr-namespace:MultiSelectLibrary.MultiSelectListBox;assembly=MultiSelectLibrary"

<mslb:MultiSelectListBox SelectionMode="Extended" .../>

If you just use some kind of code behind, you can do it like this (doing the same as the library)

<ListBox SelectionMode="Extended"
         ...>
    <ListBox.ItemContainerStyle>
        <Style TargetType="{x:Type ListBoxItem}">
            <EventSetter Event="PreviewMouseUp" Handler="ListBoxItem_PreviewMouseUp"/>
            <EventSetter Event="PreviewMouseLeftButtonDown" Handler="ListBoxItem_PreviewMouseLeftButtonDown"/>
            <EventSetter Event="PreviewMouseMove" Handler="ListBoxItem_PreviewMouseMove"/>
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>

And in code

private object _anchor, _lead;
private Boolean _inMouseSelectionMode;
private List<object> _selectedItems = new List<object>();

private void ListBoxItem_PreviewMouseUp(object sender, MouseButtonEventArgs e)
{
    _selectedItems.Clear();
    _inMouseSelectionMode = false;
    _anchor = null;
    _lead = null;
}

private void ListBoxItem_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl))
        return;

    _anchor = sender;
    _inMouseSelectionMode = true;
    _selectedItems.Clear();
    _selectedItems.Add(sender);
}
private void ListBoxItem_PreviewMouseMove(object sender, MouseEventArgs e)
{
    if (!_inMouseSelectionMode)
        return;

    if (_lead != sender)
    {
        var last = _lead;
        _lead = sender;

        if (_selectedItems.Contains(_lead))
            _selectedItems.Remove(last);
        else
            _selectedItems.Add(_lead);
    }

    foreach (var item in _selectedItems)
        ((ListBoxItem)item).IsSelected = true;
}
+5
source

Source: https://habr.com/ru/post/1779128/


All Articles