使用ListBox拖动选择

时间:2011-06-15 20:36:08

标签: wpf listview drag multi-select

我在WPF中有一个ListView的简单实现,它允许我通过按住鼠标按钮并拖动项目来选择列表中的多个项目。但是,在按住鼠标按钮的同时,当我将鼠标移到ListView之外时,选择会发生奇怪的事情。理想情况下,我只希望选择保持不变,而是快速遍历所有选定的项目,只留下最后一项。

这是代码,有什么想法吗?

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

1 个答案:

答案 0 :(得分:3)

当鼠标“拖动”超出列表顶部或列表底部下方时,会遇到您遇到的困境。我认为您设置的行为只有在选择模式为多个时才能正常工作。下面对MultiSelectListView的修改将默认选择模式设置为Multiple,并假设用户想要通过鼠标左键单击启动另一个选择。如果SelectionMode在XAML中设置为Extended或Single,您仍将体验到funkiness。

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