Hit Testing
The normal WPF mouse events and properties work when the mouse is
over a Viewport3D
just like they do
for any other UI element. The shapes of the elements in the model will
be taken into account—if your scene has areas with nothing in it, the
Viewport3D
will effectively be
transparent in those areas, and if you move the mouse over those, it
will be considered to be over whatever is behind the Viewport3D
rather than over the Viewport3D
itself. But as long as the mouse is
over some 3D object, all the usual mouse events will be reported.
Tip
You can disable hit testing by setting IsHitTestVisible
to false on the Viewport3D
. This is recommended for very
complex 3D models if hit testing is not required, as 3D hit testing
can be expensive.
Sometimes it is useful to know exactly which part of your 3D model
the mouse is over. For example, in an application that displays the
graph shown in Figure 1-21, you might want to
display the exact coordinates and value for the point currently under
the mouse. You can call the VisualTreeHelper.HitTest
method to retrieve
all the necessary information. You can pass in a 2D position relative to
the Viewport3D
(e.g., the current
mouse location), as Example 17-33 shows.
Example 17-33. Hit testing with a 2D starting point
public partial class Window1 : Window { ... void myViewport_MouseMove(object sender, MouseEventArgs e) { Point mousePos = e.GetPosition(vp); PointHitTestParameters hitParams = new PointHitTestParameters(mousePos); VisualTreeHelper.HitTest(vp, ...
Get Programming WPF, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.