In WPF 3D, we often need to change the color of a ModelVisual3D object.
Let's first talk about ModelVisual3D. In essence, 3D models are made up of triangles and are rendered by materials (DiffuseMaterial ).
This is a ModelVisual3D xaml code:
<ModelVisual3D x: Name = "d18">
<ModelVisual3D. Content>
<GeometryModel3D x: Name = "DefaultMaterial" d: Bounds = "-156.412704467773,-34.2943992614746,-13.5738000869751, 84.2265014648438, 42.2536993026733, 27.1476001739502">
<GeometryModel3D. Geometry>
<MeshGeometry3D Normals = "0,-0,-0,-0,-,-, 0, 0, 0, 0 0 0,-1, -1 0, 0,-1 0,-1 0,-1 0,-1
0, 0, 1 0,... "/>
</GeometryModel3D. Geometry>
<GeometryModel3D. Material>
<DiffuseMaterial Brush = "White"/>
</GeometryModel3D. Material>
</GeometryModel3D>
</ModelVisual3D. Content>
The hierarchical structure is ModelVisual3D-> ModelVisual3D. Content-> GeometryModel3D-> GeometryModel3D. Material
The Gemetry of GeometryModel3D defines all coordinates, and connects these coordinates to the skeleton of the Model Block. Material defines the skin of the skeleton.
For more explanations, go to msdn. I have written a general method to modify the color of the model:
Public static class RenderExtension
{
Public static void SetColor (this ModelVisual3D visual3D, Brush color)
{
GeometryModel3D geometrymodel = visual3D. Content as GeometryModel3D;
If (geometrymodel. Material is MaterialGroup)
{
Var materialGroup = geometrymodel. Material as MaterialGroup;
Foreach (var groupItem in materialGroup. Children)
{
If (groupItem is DiffuseMaterial)
{
DiffuseMaterial tmpItem = groupItem as DiffuseMaterial;
TmpItem. Brush = color;
}
}
}
Else
{
DiffuseMaterial material = geometrymodel. Material as DiffuseMaterial;
If (material! = Null)
{
Material. Brush = color;
}
}
}
}
You only need to write: visual3D. SetColor (Brushes. Red );