ViewPort3D:如何从Code后面创建一个带有文本的WPF对象(Cube)

时间:2012-07-23 15:21:20

标签: c# wpf wpf-controls viewport3d helix-3d-toolkit

我想绘制一组3D立方体,每个立方体应该显示一个名称,并且在选择立方体时也应该有自己的事件处理程序。

是否可以使用代码隐藏或xaml绑定来实现它?

1 个答案:

答案 0 :(得分:6)

要从代码后面绘制3D立方体,我将使用Helix3D工具包CubeVisual3D。但是,如果你想坚持使用股票WPF 3D元素,它实现起来相当简单。

从这里开始了解3D环境中的文字http://www.codeproject.com/Articles/33893/WPF-Creation-of-Text-Labels-for-3D-Scene,它将指导您通过两种不同的方法将文字添加到3D图像中,我觉得非常有帮助。

对于一个立方体只需使用RectangleVisual3D对象就像这样。

    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.

添加事件处理程序我相信您必须将Handler添加到Viewport3D。这种性质的东西应该有效。

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

然后添加此功能

    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;
    }

然后添加事件处理程序

    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
    }