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.
Asked
Active
Viewed 1,133 times
0
-
What is the end result UI that you want? In other words, why do you only want to handle some clicks? Do you only want some parts to be selectable, or do you want to add a context menu to particular items? – Andrew Aug 15 '13 at 05:45
-
1Well what's wrong with just a `MouseDown` handler on the `TreeView`(make it a behavior if your against code-behind)? If your `TreeViewItem` handles the click, this would not get invoked and if none of them do handle it, it will invoke this event handler and you can do what you need. <- This works fine for me. If for some reason you see the event getting invoked even when the click is over a `TreeViewItem` you could use an approach like [This](http://stackoverflow.com/a/594682/1834662) to check via `VisualTreeHelper` if the click belongs to a `TreeViewItem` or not and act accordingly. – Viv Aug 15 '13 at 08:56
-
andrew, is there a way to make it so that some parts are not selectable? I'm still a little hazy on how mouseevents work. how does the program determine where the previewclick event will tunnel down to before bubbling back up? does it hit test a location and then look for the item farthest in the visual tree or does it have some index in hit testing to tell what's on top? anyway I will go read on hit testing since the answer below seems to reference that – James Joshua Street Aug 15 '13 at 19:44
1 Answers
2
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.

Sheridan
- 68,826
- 24
- 143
- 183