0
votes

I have an object called "TextModel". I defined a HierarchicalDataTemplate for it.

like this:

<HierarchicalDataTemplate DataType="{x:Type local:TextModel}"
                          ItemsSource="{Binding Children}">
  <TextBlock x:Name="TextPresenter"
             Text="{Binding Text}"
             Style="{StaticResource TextModelStyleMouseOver}" />
</HierarchicalDataTemplate>

This TextModel contained in each TreeViewItem in my TreeView. And, in the code-behind I used VisualTreeHelper.HitTest to get the TreeViewItem that I clicked on, but it's not giving me the TreeViewItem as one of the HitTest results. The HitTest results are: the TextBlock (and Border, Grid and ScrollViewer) - the one from the HierarchicalDataTemplate that I defined.

I've tried to use LogicalTreeHelper.GetParent(textBlockFromTheHitTestResults) but it returned me a null.

Thanks for your attention!

1

1 Answers

0
votes

HitTest has an overload you can use to filter results:

VisualTreeHelper.HitTest(
    root,
    o => o is TreeViewItem ? HitTestFilterBehavior.ContinueSkipChildren : HitTestFilterBehavior.Continue,
    r =>
        {
            if (r.VisualHit is TreeViewItem)
            {
                DoSomethingWithTreeViewItem((TreeViewItem)r.VisualHit);
                return HitTestResultBehavior.Stop;
            }

            return HitTestResultBehavior.Continue;
        },
    new PointHitTestParameters(point));