开发者

Drag-select with ListBox

I have a simple implementation of a ListView in WPF that allows me to select multiple items in the list by holding the mouse button and dragging over the items. However, while holding the mouse button down, when I move the mouse outside the ListView, something strange happens with the selection. Ideally, I would just want the selection to remain the same, but instead it quickly cycles through all the selected items, leaving only the last item selected.

Here's the code, have any ideas?

public class MultiSelectListView : ListView
{
   private bool m_isSelectionActive;

   public bool IsSelectionActive
   {
      get { return m_isSelectionActive; }
   }

   protected override DependencyObject GetContainerForItemOverride()
   {
      return new MultiSelectListViewItem(this);
   }

   protected override void OnPreviewMouseLeftButtonDown(MouseButtonEventArgs e)
   {
      m_isSelectio开发者_JAVA百科nActive = true;
   }

   protected override void OnPreviewMouseLeftButtonUp(MouseButtonEventArgs e)
   {
      m_isSelectionActive = false;
   }
}

public class MultiSelectListViewItem : ListViewItem
{
   private readonly MultiSelectListView m_parent;

   public MultiSelectListViewItem(MultiSelectListView parent)
   {
      m_parent = parent;
   }

   protected override void OnMouseEnter(System.Windows.Input.MouseEventArgs e)
   {
      if (m_parent.IsSelectionActive)
         IsSelected = true;
   }
}


The funkiness you are experiencing happens when the mouse "drag" goes above the top of the list or below the bottom of the list. I think the behavior you set up will only work well if the selection mode is Multiple. The modifications to the MultiSelectListView below set the default selection mode to Multiple and assumes the user wants to start another selection with a left mouse click. You will still experience funkiness if the SelectionMode is set to Extended or Single in the XAML.

public class MultiSelectListView : ListView
{
    private bool m_isSelectionActive;
    public bool IsSelectionActive
    {
        get
        {
            return m_isSelectionActive;
        }
    }
    protected override DependencyObject GetContainerForItemOverride()
    {
        return new MultiSelectListViewItem(this);
    }
    protected override void OnPreviewMouseLeftButtonDown(MouseButtonEventArgs e)
    {
        if (SelectionMode != SelectionMode.Single)
        {
            SelectedItems.Clear();
        }
        m_isSelectionActive = true;
    }
    protected override void OnPreviewMouseLeftButtonUp(MouseButtonEventArgs e)
    {
        m_isSelectionActive = false;
    }
    public MultiSelectListView() : base()
    {
        SelectionMode = SelectionMode.Multiple;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜