c# - ViewPort3D:如何从后面的代码创建带有文本的 WPF 对象(立方体)

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

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

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

最佳答案

要从后台代码绘制 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.

添加事件处理程序 我相信您必须将处理程序添加到 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
    }

关于c# - ViewPort3D:如何从后面的代码创建带有文本的 WPF 对象(立方体),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11615519/

相关文章:

c# - 优化在 MySQL 中存储 Guid : "Data too long for column" even if it should fit to CHAR(16)

c# - SqlException : Cannot open database <database> requested by the login. 登录失败

c# - ASCII.GetString() 在空字符处停止

wpf - 如何确保我的 WPF TabControl 在包含至少一个选项卡时始终具有选定的选项卡?

c# - XAML 中的映射命名空间不起作用

c# - 使用 C# 将记录插入 SQL Server 2012

wpf - 如何让我的 ScrollViewer 滚动查看区域?

wpf - 如何将 GridSplitter 设置为特定的初始位置?

c# - Combobox 不反射(reflect)初始对象值

c# - 添加到 WPF Canvas 的图像更改大小