拖动并选择ListBox项?

时间:2010-12-08 06:12:29

标签: wpf

如果开始从一个项目拖动到拖动结束,如何选择列表框中的项目?

1 个答案:

答案 0 :(得分:5)

我在msdn上的一个问题上找到了这个方法,但我再也找不到它了所以我无法链接它..无论如何,这个工作得很好,只有在同时拖动和滚动时出现问题,然后呢可能会错过一些项目。我已经创建了一个名为MultiSelectLibrary的自定义控件库,您可以像这样使用

添加对MultiSelectLibrary的引用,可以从here下载(来源here
使用SelectionMode =“Extended”添加命名空间和MultiSelectListBox,它应该可以工作。

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

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

如果你只是使用一些代码,你可以这样做(做与库相同的事情)

<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>

在代码背后

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;
}