0

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!

Daniel
  • 10,864
  • 22
  • 84
  • 115
Yanko Pata
  • 175
  • 1
  • 10

1 Answers1

0

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));
Kent Boogaart
  • 175,602
  • 35
  • 392
  • 393
  • The returned r.VisualHit-s are just like I mentioned before: TextBlock, and Border, Grid and ScrollViewer. But there is something interesting - the o actually finds TreeViewItem, but then the HitTestResultCallback called with r that is Grid (one of the hit test results written above). So what I did is taking the o that found as TreeViewItem and keeping it in local variable that will be the returned value of the wrapping method of this code you gave me. – Yanko Pata Jan 23 '13 at 11:20