Search code examples
c#wpf3dviewporthittest

How to HitTest XAML 3D object in WPF


What I want to do is to know if the user click the red button of my joystick. (for the purpose, I draw over the real joystick graphic to keep our drawing private) Our XAML 3D joystick

This joystick is a XAML 3D.

The red button is a GeometryModel3D object, with the x:Name "Geo_Btn_CSS_TAKE". When I click on the joystick, I can do a HitTest, he gives me all the GeometryModel3D object but I can't access to the x:Name, so I cannot know witch one is the good one...

Visual tree of my object

And this is how I do my HitTest:

private void OnTouchMouseDown(EventArgs e)
{
    Viewport3D viewport3D = WtoHitTest((Grid)Parent, e) as Viewport3D; // My own HitTest works well, I get my viewport3D

    Point mouseposition = WtoHelper.GetPositionFromEvent(e, viewport3D); // Get the point if it's a mouse event or touch event
    Point3D testpoint3D = new Point3D(mouseposition.X, mouseposition.Y, 0);
    Vector3D testdirection = new Vector3D(mouseposition.X, mouseposition.Y, 10);
    PointHitTestParameters pointparams = new PointHitTestParameters(mouseposition);
    RayHitTestParameters rayparams = new RayHitTestParameters(testpoint3D, testdirection);

    VisualTreeHelper.HitTest(viewport3D, null, HTResult, pointparams);
}

public HitTestResultBehavior HTResult(System.Windows.Media.HitTestResult rawresult)
{
    RayHitTestResult rayResult = rawresult as RayHitTestResult;

    if (rayResult != null)
    {
        RayMeshGeometry3DHitTestResult rayMeshResult = rayResult as RayMeshGeometry3DHitTestResult;

        if (rayMeshResult != null)
        {
            GeometryModel3D hitgeo = rayMeshResult.ModelHit as GeometryModel3D;

            **// HERE I NEED TO KNOW WHAT IS MY GEOMETRYMODEL3D'S X:NAME**
            // ANY IDEA???
        }
    }
    return HitTestResultBehavior.Continue;
}

What else I know:

  • My 3D object does not have a position (x,y) that I can bind to
  • I cannot insert non-3D element in the Viewport3D
  • I cannot access to the x:Name of a 3D object
  • 3D object or not FrameworkElement or Visual. They are Media3D

The way I did it, I only need to know the x:name to complete my implementation... if someone have a tips or an other way to go, let me know.

Thank you

EDIT: this is the properties of my 3D object: enter image description here


Solution

  • The one thing that I can think of that will work and is XAML friendly is to define your own attached property on GeometryModel3D. Look here for how to create custom attached properties.