ViewPort3D: How to create a WPF Object (Cube) with text on it from Code behind

老子叫甜甜 提交于 2020-01-24 13:42:53

问题


I want to draw a set of 3D-Cubes, each Cube should display a name and also should have its own event handler when the cube is selected.

Is it possible to implement it using code behind or xaml binding?


回答1:


To draw a 3D cube from code behind I would use the Helix3D toolkit CubeVisual3D. However if you want to stick with stock WPF 3D elements it is fairly simple to implement.

start here to Learn about Text in 3D enviroments http://www.codeproject.com/Articles/33893/WPF-Creation-of-Text-Labels-for-3D-Scene which will guide you through two different approaches to adding Text to a 3D image and I find very helpful.

For a cube Just use a RectangleVisual3D object Something like this.

    RectangleVisual3D myCube = new RectangleVisual3D();
    myCube.Origin = new Point3D(0, 0, 0); //Set this value to whatever you want your Cube Origen to be.
    myCube.Width = 5; //whatever width you would like.
    myCube.Length = 5; //Set Length = Width
    myCube.Normal = new Vector3D(0, 1, 0); // if you want a cube that is not at some angle then use a vector in the direction of an axis such as this one or <1,0,0> and <0,0,1>
    myCube.LengthDirection = new Vector3D(0, 1, 0); //This will depend on the orientation of the cube however since it is equilateral just set it to the same thing as normal.
    myCube.Material = new DiffuseMaterial(Brushes.Red); // Set this with whatever you want or just set the myCube.Fill Property with a brush type.

Too add the event handler I believe you must add the Handler to the Viewport3D. Something of this nature should work.

    public Window1()
    {
    InitializeComponent();
    this.mainViewport.MouseDown += new MouseButtonEventHandler(mainViewport_MouseDown);
    this.mainViewport.MouseUp += new MouseButtonEventHandler(mainViewport_MouseUp);
    }

Then Add this function

    ModelVisual3D GetHitResult(Point location)
    {
    HitTestResult result = VisualTreeHelper.HitTest(mainViewport, location);
    if(result != null && result.VisualHit is ModelVisual3D)
    {
    ModelVisual3D visual = (ModelVisual3D)result.VisualHit;
    return visual;
    }

    return null;
    }

Then Add in the Event Handlers

    void mainViewport_MouseUp(object sender, MouseButtonEventArgs e)
    {
    Point location = e.GetPosition(mainViewport);
    ModelVisual3D result = GetHitResult(location);
    if(result == null)
    {
    return;
    }
    //Do Stuff Here
    }

    void mainViewport_MouseDown(object sender, MouseButtonEventArgs e)
    {
    Point location = e.GetPosition(mainViewport);
    ModelVisual3D result = GetHitResult(location);
    if(result == null)
    {
    return;
    }
    //Do Stuff Here
    }


来源:https://stackoverflow.com/questions/11615519/viewport3d-how-to-create-a-wpf-object-cube-with-text-on-it-from-code-behind

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!