How to get TreeViewItem using a coordinate/point via HitTesting in WPF?

后端 未结 1 848
难免孤独
难免孤独 2021-01-14 03:44

I am trying to get the TreeViewItem under the mouse, but can\'t find a way to do it.

Currently I am using this:

Layer GetItemAtLocation          


        
相关标签:
1条回答
  • 2021-01-14 04:12

    You don't specify what led you to need this, which would help a little.

    This is kind of nasty, but you could do this:

    IInputElement dropNode = tree.InputHitTest(point);
    

    This will probably give you a TextBlock, so you would then have to use VisualTreeHelper.GetParent() to navigate up through the TextBlock, ContentPresenter, Border, Grid, and then eventually the TreeViewItem.

    This is certainly not the nicest approach, but it should work.

    Depending on what you are doing, Mike Hillberg's blog provided an attached property approach that be used in a trigger. See here

    In his example, he is turning a TreeViewItem green when the mouse is over it.

    <TreeView.Resources>
          <Style TargetType="TreeViewItem">
            <Style.Triggers>
              <Trigger Property="local:MyTreeViewHelper.IsMouseDirectlyOverItem" Value="True">
                <Setter Property="Background" Value="Green" />
              </Trigger>
            </Style.Triggers>
          </Style>
        </TreeView.Resources>
    

    The MyTreeViewHelper class keeps track of the MouseEnter/MouseLeave events, and gives a nice Property that can be used in triggers and things, like the one above.

    I hope that helps.

    0 讨论(0)
提交回复
热议问题