Drag and Select ListBox Items?
how to select items in listbox, if start dragging from one item to the end of the dragging?
I found this approach on a question on msdn but I can't find it again so I can't link it.. Anyway, this works pretty good, only problem being when dragging and scrolling at the same time, then it can miss a few items. I've created a custom control library called MultiSelectLibrary which you can use like this
Add a reference to MultiSelectLibrary which can be downloaded from here (Source here)
Add the namespace and the MultiSelectListBox with SelectionMode="Extended" and it should work.
xmlns:mslb="clr-namespace:MultiSelectLibrary.MultiSelectListBox;assembly=MultiSelectLibrary"
<mslb:MultiSelectListBox SelectionMode="Extended" .../>
If you rather just use some code behind you can do it like this (doing the same thing 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 behind
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;
}
精彩评论