static UIElement GetClosest( ItemsControl itemsControl, List<DependencyObject> items, Point position, Orientation searchDirection) { UIElement closest = null; var closestDistance = double.MaxValue; foreach (var i in items) { var uiElement = i as UIElement; if (uiElement != null) { if (!itemsControl.IsAncestorOf(uiElement)) continue; var p = uiElement.TransformToAncestor(itemsControl).Transform(new Point(0, 0)); var distance = double.MaxValue; if (itemsControl is TreeView) { var xDiff = position.X - p.X; var yDiff = position.Y - p.Y; var hyp = Math.Sqrt(Math.Pow(xDiff, 2d) + Math.Pow(yDiff, 2d)); distance = Math.Abs(hyp); } else { switch (searchDirection) { case Orientation.Horizontal: distance = Math.Abs(position.X - p.X); break; case Orientation.Vertical: distance = Math.Abs(position.Y - p.Y); break; } } if (distance < closestDistance) { closest = uiElement; closestDistance = distance; } } } return closest; }