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