Reputation: 3409
I'm wondering how I would go about this. I can't very well check that mouse is not over item1, item2, ...., can I? there should be some better way of doing this. I just want to deselect all the items if the user clicks on non-item space.
Upvotes: 0
Views: 1389
Reputation: 69959
You can do what you want... in your Click
handler, add this code:
HitTestResult hitTestResult = VisualTreeHelper.HitTest(uiElement, DragStartPosition);
TreeViewItem listBoxItem = hitTestResult.VisualHit.GetParentOfType<TreeViewItem>();
if (listBoxItem == null)
{
// user has clicked, but not on a TreeViewItem
}
The GetParentOfType
method is an extension method that I created and is as follows:
public static T GetParentOfType<T>(this DependencyObject element) where T : DependencyObject
{
Type type = typeof(T);
if (element == null) return null;
DependencyObject parent = VisualTreeHelper.GetParent(element);
if (parent == null && ((FrameworkElement)element).Parent is DependencyObject)
parent = ((FrameworkElement)element).Parent;
if (parent == null) return null;
else if (parent.GetType() == type || parent.GetType().IsSubclassOf(type))
return parent as T;
return GetParentOfType<T>(parent);
}
Please note that extension methods need to be placed into a static
class... you could always refactor it into a normal method if you prefer.
Upvotes: 2