How to detect double click on list view scroll bar

2019-04-20 12:12发布

问题:

I have two list view on WPF. The first listview is loaded with a Datatable. When double clicking on one item from the first listview, the selectedItem is moved to the second listview.

The problem arises when appears an scroll bar in the first list view due to a lot of elements loaded from the DataTable. If a select one item and double click on the scroll bar down arrow, MouseDoubleClick event is launched and the selected item is moved to the second listview.

How I can detect the double click on the scroll bar to prevent this?

Thanks a lot!

回答1:

I tested the above code which was very helpful, but found the following to be more stable, as sometimes the source gets reported as GridViewRowPresenter when in fact you are double clicking an item.

var src = VisualTreeHelper.GetParent((DependencyObject)e.OriginalSource);
var srcType = src.GetType();
if (srcType == typeof(ListViewItem) || srcType == typeof(GridViewRowPresenter))
{
    // Your logic here
}


回答2:

Try this in you MouseDoubleClick event on the first Listview:

DependencyObject src = VisualTreeHelper.GetParent((DependencyObject)e.OriginalSource);

if(src is Control && src.GetType() == typeof(ListViewItem))
{
    // Your logic here
}

Based on this.

I am using this in various projects and it solves the problem you are facing.



回答3:

private void ListBox_OnMouseDoubleClick(object pSender, MouseButtonEventArgs pE)
{
  FrameworkElement originalSource = pE.OriginalSource as FrameworkElement;
  FrameworkElement source = pE.Source as FrameworkElement;

  if (originalSource.DataContext != source.DataContext)
  {
      logic here
  }         
}

When you have the DataContext you can easy see if the sender is an item or the main listbox



回答4:

I've got the final solution:

private void ListView_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
    var originalSource = (DependencyObject)e.OriginalSource;
    while ((originalSource != null) && !(originalSource is ListViewItem)) originalSource = VisualTreeHelper.GetParent(originalSource);
    if (originalSource == null) return;
}

it works for me.