新建一个WPF工程;
引入3D Tools;前面已经说了,引入之后,不用写代码即可实现3D物体的鼠标操作;
xaml代码如下;
<Window x:Class="thrbtn.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="3D立方体上加按钮" Height="450" Width="450"
xmlns:tools="clr-namespace:_3DTools;assembly=3DTools"
>
<Grid>
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
</Grid.RowDefinitions>
<Border BorderBrush="Yellow" BorderThickness="1" Margin="5">
<tools:TrackballDecorator>
<Viewport3D>
<Viewport3D.Camera>
<PerspectiveCamera
LookDirection="2,-1,-1"
UpDirection="0,1,0"
Position="-20,15,15"
NearPlaneDistance="1"
FarPlaneDistance="100"
FieldOfView="40"
>
</PerspectiveCamera>
</Viewport3D.Camera>
<ModelVisual3D>
<ModelVisual3D.Content>
<DirectionalLight
Color="Yellow"
Direction="-2,-3,-1" />
</ModelVisual3D.Content>
</ModelVisual3D>
<ModelVisual3D>
<ModelVisual3D.Content>
<DirectionalLight
Color="Green"
Direction="2,1,1" />
</ModelVisual3D.Content>
</ModelVisual3D>
<ModelVisual3D>
<ModelVisual3D.Content>
<GeometryModel3D>
<GeometryModel3D.Geometry>
<MeshGeometry3D Positions="0,0,0 10,0,0 0,10,0 10,10,0
0,0,10 10,0,10 0,10,10 10,10,10"
TriangleIndices="0,2,1 1,2,3
0,1,4 1,5,4 1,7,5 1,3,7
4,5,6 7,6,5 2,6,3 3,6,7"
Normals="0,1,0 0,1,0 1,0,0 1,0,0
0,1,0 0,1,0 1,0,0 1,0,0" />
</GeometryModel3D.Geometry>
<GeometryModel3D.Material>
<DiffuseMaterial Brush="LightBlue" />
</GeometryModel3D.Material>
</GeometryModel3D>
</ModelVisual3D.Content>
<ModelVisual3D.Transform>
<RotateTransform3D>
<RotateTransform3D.Rotation>
<AxisAngleRotation3D Angle="{Binding ElementName=sliderRotate, Path=Value}"
Axis="0 1 0" />
</RotateTransform3D.Rotation>
</RotateTransform3D>
</ModelVisual3D.Transform>
</ModelVisual3D>
<Viewport2DVisual3D>
<Viewport2DVisual3D.Geometry>
<MeshGeometry3D
Positions="0,0,0 0,0,10 0,10,0 0,10,10"
TriangleIndices="0,1,2 2,1,3"
TextureCoordinates="0,1 1,1 0,0 1,0"
/>
</Viewport2DVisual3D.Geometry>
<Viewport2DVisual3D.Material>
<DiffuseMaterial Viewport2DVisual3D.IsVisualHostMaterial="True" />
</Viewport2DVisual3D.Material>
<Viewport2DVisual3D.Visual>
<Border BorderBrush="Yellow" BorderThickness="1">
<StackPanel Margin="10">
<TextBlock Margin="3"> 2D content 呈现在3D表面</TextBlock>
<Button Margin="3" Click="cmd_Click">Click Me</Button>
<TextBox Margin="3">......;</TextBox>
</StackPanel>
</Border>
</Viewport2DVisual3D.Visual>
</Viewport2DVisual3D>
</Viewport3D>
</tools:TrackballDecorator>
</Border>
<Slider Margin="5" Grid.Row="1" Minimum="0" Maximum="360" Orientation="Horizontal" Name="sliderRotate" ></Slider>
</Grid>
</Window>
首先是一个grid,grid是一个四方形布局控件,对grid进行了行划分;第1行显示3D立方体;第2行显示一个滑动条控件;
grid的第一行;先用Border控件画一个边框;
然后使用3D Tools的<tools:TrackballDecorator>标签,这样此标签里的3D物体可以直接用鼠标操作;
然后是<Viewport3D>,这里面是呈现3D内容的;
在 <Viewport3D> 里;先定义摄像机,光源,然后画3d立方体;
然后添加一个 <Viewport2DVisual3D> 元素;
在<Viewport2DVisual3D>里,先设置纹理坐标;
然后用一个垂直面板控件,三行分别放一个文本块控件、一个按钮、一个文本框;
按钮单击事件在cs文件里只是弹一个消息框;
运行一下如下;
可用鼠标旋转翻转;