2

I need my app to perform a certain action when DataGrid is double clicked. The action should not be performed if a scrollbar is doubleclicked. So I try to see what is doubleclicked:

private void DataGrid_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            Point p = Mouse.GetPosition(this.DataGrid1);
            IInputElement ie = this.DataGrid1.InputHitTest(p);
        }

But when I doubleclick a scrollbar, then IInputElement appears to be all sort of stuff: Microsoft.Windows.Themes.ScrollChrome or System.Windows.Shapes.Rectangle . So I am not sure if I clicked a scrollbar.

So how do I check if I really doubleclicked a scrollbar?

Bogdan Verbenets
  • 25,686
  • 13
  • 66
  • 119

1 Answers1

4

There's no need to use hit test here, just check if e.OriginalSource has a parent of ScrollBar type by traversing the visual tree. There's one potential issues with this approach - your UI element has to be loaded, which is typically the case when dealing with mouse events anyway. Heres' the code which checks if an UIElement has a parent of a specific type.

public static T GetParentOfType<T>(DependencyObject current)
          where T : DependencyObject
        {
            for (DependencyObject parent = VisualTreeHelper.GetParent(current);
                parent != null;
                parent = VisualTreeHelper.GetParent(parent))
            {
                T result = parent as T;

                if (result != null)
                    return result;
            }

            return null;
        }
  • Thanks for the answer! By the way, if I doubleclick a text cell, then I get a TextBlock in e.OriginalSource, and VisualTreeHelper.GetParent returns null for it. Do you know why? – Bogdan Verbenets Jan 17 '12 at 15:20
  • @Bogdan0x400 what type do you pass as T? –  Jan 17 '12 at 15:22
  • I don't use this code, I just try VisualTreeHelper.GetParent(e.OriginalSource) when I doubleclick a cell and it returns null, to my surprise. – Bogdan Verbenets Jan 17 '12 at 15:28
  • 1
    It shouldn't really do that, should it. In WPF Parent can be set to pretty much anything (in comparison with WinForms) and it has no bearing on the visual tree (DP system is quite loose and it's one the realisations of this fact). Did you see this post? One of the answers suggests to go the opposite way from top to bottom: http://stackoverflow.com/questions/636383/wpf-ways-to-find-controls –  Jan 17 '12 at 15:38