Standart WPF tree do not support multiselection, so I had to do it by my own.
In this note I'd like to tell how to implement HitTest in WPF tree.
I've got the simple class, ingerited from TreeView
public class MultiSelectTreeView : TreeView
I've got to handle Control key to allow multiselection
bool IsCtrlPressed
{
get
{
return Keyboard.IsKeyDown(Key.LeftCtrl)
|| Keyboard.IsKeyDown(Key.RightCtrl);
}
}
We add our own functionality to OnMouseUp method (just believe me, handle OnMouseDown - that's a bad idea)
In my tree I use Model-View-ViewModel pattern - and ItemViewModel class is the ViewModel for my tree. (More info about it: here)
protected override void OnMouseUp(MouseButtonEventArgs e)
{
base.OnMouseUp(e);
ItemViewModel selectedItem =
GetItemAtLocation(e.GetPosition(this));
if (selectedItem != null)
this.SelectItem(selectedItem);
}
Let's have a look at GetItemAtLocation(Point point) method. The HitTest is used right here. Terribly simple:
private ItemViewModel GetItemAtLocation(Point point)
{
HitTestResult hitTestResult =
VisualTreeHelper.HitTest(this, point);
if (hitTestResult.VisualHit is FrameworkElement)
{
FrameworkElement element =
hitTestResult.VisualHit as FrameworkElement;
return element.DataContext as ItemViewModel;
}
return null;
}