Search code examples
wpflistviewclickdouble-clicklistviewitem

WPF ListView DoubleClick OriginalSource problem


I attached an EventHandler to the MouseDoubleClick event.

<Style TargetType="ListViewItem" BasedOn="{StaticResource MyStyle}">                                
    <EventSetter Event="MouseDoubleClick" Handler="ListViewItem_MouseDoubleClick" />
</Style>

private void ListViewItem_MouseDoubleClick(object sender, RoutedEventArgs e) {}

The ListView's View is based on the GridView, one of the column contains a CheckBox. I want to be able to ignore the double click if the CheckBox is double-clicked.

The problem is that I cannot find the original source (CheckBox) to block it, as with routing event I got the Theme as the original source, and with direct I got the ListViewItem.


Solution

  • You can use the VisualTreeHelper to find out if any ancestor of the OriginalSource is a CheckBox like this:

    private void ListViewItem_MouseDoubleClick(object sender, RoutedEventArgs e)
    {
        var obj = e.OriginalSource as DependencyObject;
    
        // suppress event?
        if (IsWithinCheckBox(obj))
            return;
    
        // handle your event here
    }
    
    private bool IsWithinCheckBox(DependencyObject obj)
    {
        while (obj != null)
        {
            if (obj is CheckBox)
                return true;
    
            obj = VisualTreeHelper.GetParent(obj);
        }
    
        return false;
    }