1

I am trying to draw a triangle in WPF in C# just to learn how to use this tool. If you check the last statement, I can't run program because of it. I think I am missing a using directive or maybe an assembly reference ...

These are the using directives I am employing:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Media.Media3D;

Here is my code:

System.Windows.Media.Media3D.Point3D point0 = new Point3D(-0.5, 0, 0);
System.Windows.Media.Media3D.Point3D point1 = new Point3D(0.5, 0.5, 0.3);
System.Windows.Media.Media3D.Point3D point2 = new Point3D(0, 0.5, 0);


System.Windows.Media.Media3D.MeshGeometry3D triangleMesh = new MeshGeometry3D();

triangleMesh.Positions.Add(point0);
triangleMesh.Positions.Add(point1);
triangleMesh.Positions.Add(point2);

int n0 = 0;
int n1 = 1;
int n2 = 2;

triangleMesh.TriangleIndices.Add(n0);
triangleMesh.TriangleIndices.Add(n1);
triangleMesh.TriangleIndices.Add(n2);

System.Windows.Media.Media3D.Vector3D norm = new Vector3D(0, 0, 1);
triangleMesh.Normals.Add(norm);
triangleMesh.Normals.Add(norm);
triangleMesh.Normals.Add(norm);

System.Windows.Media.Media3D.Material frontMaterial = new DiffuseMaterial(new SolidColorBrush(Colors.Blue));

System.Windows.Media.Media3D.GeometryModel3D triangleModel = new GeometryModel3D(triangleMesh, frontMaterial);

triangleModel.Transform = new Transform3DGroup();

System.Windows.Media.Media3D.ModelVisual3D visualModel = new ModelVisual3D();
visualModel.Content = triangleModel;

this.mainViewport.Children.Add(visualModel); // here I have an error !
4

2 回答 2

0

在你的 xaml 文件中,像这样覆盖你的网格,你的黑色三角形就会出现。我测试了它。

<Grid>
        <Viewport3D Name="mainViewport" ClipToBounds="True">
            <Viewport3D.Camera>
                <PerspectiveCamera 
  FarPlaneDistance="100"
  LookDirection="-11,-10,-9"
  UpDirection="0,1,0"
  NearPlaneDistance="1" 
  Position="11,10,9" 
  FieldOfView="70" />
            </Viewport3D.Camera>
            <ModelVisual3D>
                <ModelVisual3D.Content>
                    <DirectionalLight 
    Color="White" 
    Direction="-2,-3,-1" />
                </ModelVisual3D.Content>
            </ModelVisual3D>
        </Viewport3D>
</Grid>
于 2013-05-06T01:07:44.027 回答
0

这很奇怪,它对我不起作用!但是如果我用下面的代码替换最后一条语句,它没有显示错误,因为我声明了 mainViewport,但是现在当我运行程序时,三角形没有出现!(我的 xaml 文件看起来就像 Drew Pierce 所写的一样)。

任何想法为什么三角形没有出现?

        System.Windows.Media.Media3D.Viewport3DVisual mainViewport = new Viewport3DVisual();

        mainViewport.Children.Add(visualModel);
于 2013-05-08T20:02:43.283 回答