My WPF app is simulating a map, using Shapes (Rectangles and Lines). For comfortable using I should add zooming and dragging map.
This is my XAML code:
<Border Margin="10" BorderThickness="2" BorderBrush="Black">
<Canvas Grid.Column="0" x:Name="mainCanvas" Background="Transparent" MouseWheel="Canvas_MouseWheel">
<Canvas.RenderTransform>
<MatrixTransform/>
</Canvas.RenderTransform>
</Canvas>
</Border>
I wrote working code for zomming:
int zoom = 1;
private void Canvas_MouseWheel(object sender, MouseWheelEventArgs e)
{
var element = (UIElement)sender;
var position = e.GetPosition(element);
var transform = (MatrixTransform)element.RenderTransform;
var matrix = transform.Matrix;
if(e.Delta >= 0)
{
if (zoom <= 10)
{
zoom++;
matrix.ScaleAtPrepend(1.1, 1.1, position.X, position.Y);
transform.Matrix = matrix;
}
}
else
{
if (zoom > 1)
{
zoom--;
matrix.ScaleAtPrepend(1.0/1.1, 1.0 / 1.1, position.X, position.Y);
transform.Matrix = matrix;
}
}
}
I faced with problem: when I`m zooming my canvas, canvas go beyond border. Moreover, I hae no idea how to drag canvas. So, also I want to move my map (canvas) when I moving mouse down. How can I make it?
I tried to use PanAndZoom cotrol from NuGet, but it didnt work (I can`t even add to my form in XAML). Maybe because of I use .Net 7.