Search code examples
c#wpfwpf-controlswpftoolkit

Wpf3d Zooming for window


I am trying to implement zoom functionality to my wpf 3d object. It is working fine when I trigger it from my object. But I want to do this functionality for my whole space including the object. How can I implement this zooming functionality for the whole window so if I mouse wheel from any place of window, my object will be zoom in and azoom out. Here is my code for MouseWheel Event:

    private void Grid_MouseWheel(object sender, MouseWheelEventArgs e)
    {
       TheCamera.Position = new Point3D((TheCamera.Position.X - e.Delta / 360D), (TheCamera.Position.Y - e.Delta / 360D), (TheCamera.Position.Z - e.Delta / 360D));
    }

Here is my xaml code,

`

    <Viewport3D x:Name="MainViewport">
        <Viewport3D.Camera>
            <PerspectiveCamera x:Name="TheCamera" Position="-40,40,40" LookDirection="40,-40,-40 " 
                     UpDirection="0,0,1" />
        </Viewport3D.Camera>
        <ModelVisual3D>
            <ModelVisual3D.Content>
                <Model3DGroup>
                    <DirectionalLight Color="White" Direction="-1,-1,-3" />
                    <GeometryModel3D x:Name="mGeo">
                        <GeometryModel3D.Geometry>
                            <MeshGeometry3D Positions="0,0,0 10,0,0 10,10,0 0,10,0 0,0,10 
                    10,0,10 10,10,10 0,10,10"
                    TriangleIndices="0 1 3 1 2 3  0 4 3 4 7 3  4 6 7 4 5 6 
                                     0 4 1 1 4 5  1 2 6 6 5 1  2 3 7 7 6 2"/>
                        </GeometryModel3D.Geometry>
                        <GeometryModel3D.Material>
                            <DiffuseMaterial Brush="Red"/>
                        </GeometryModel3D.Material>
                    </GeometryModel3D>
                </Model3DGroup>
            </ModelVisual3D.Content>
        </ModelVisual3D>
    </Viewport3D>

</Grid>

`


Solution

  • You grid has no background brush set on it, therefore the wheel event is not firing as it is not being detected during hit testing.

    <Grid MouseWheel="Grid_MouseWheel" Background="#00000000">
    

    Set your grid with a background like the one above and you should find that it works

    EDIT: Alternately you could hook the event to the MouseWheel event of the window instead

    <Window Title="MainWindow" Height="350" Width="525" MouseWheel="Grid_MouseWheel">