amnesia
amnesia

Reputation: 1988

WPF TextBlock.IsHitTestVisible doesn't seem to work

Maybe I'm misunderstanding how this is supposed to work, but from everything I've read it's my understanding that setting the IsHitTestVisible property to false should essentially make that element "invisible" to mouse events, and MSDN states that this property "declares whether this element can possibly be returned as a hit test result".

I have a procedurally generated Grid, each cell contains a Border, and each Border's child is a TextBlock.

This is how I'm creating the cell:

var cellBorder = new Border { BorderBrush = Brushes.LightGray, Background = Brushes.WhiteSmoke, BorderThickness = thickness };
var label = new TextBlock { Text = time.ToShortTimeString(), Foreground = Brushes.Tomato, IsHitTestVisible = false };
cellBorder.Child = label;
_grid.Children.Add(cellBorder);
Grid.SetColumn(cellBorder, j);
Grid.SetRow(cellBorder, i);

In an DragMove event handler, I want to change background color of the current cell. This was working fine before I added the TextBlock to the border. It looks something like this:

    void _grid_DragOver(object sender, DragEventArgs e)
    {
        var pos = e.GetPosition(_grid);
        var result = VisualTreeHelper.HitTest(_grid, pos);

        if (result != null)
        {
            var border = result.VisualHit as Border;
            if (border != null)
                border.Background = Brushes.LightYellow;
            else if (result.VisualHit is TextBlock)
                Console.WriteLine("Textblock hit");  // Why is this happening?
        }
    }

The TextBlock is getting returned from the hit test. Why?

Upvotes: 2

Views: 2564

Answers (1)

thumbmunkeys
thumbmunkeys

Reputation: 20764

The VisualTreeHelper does not take IsHitTestVisible into account.

If you want to omit the TextBlock from the hit test for VisualTreeHelper then you should pass filter callbacks to HitTest()

Upvotes: 3

Related Questions