You could try to see if the following code works for you.
MainWindow.xaml:
<Window x:Class="BackgroundPixels.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:BackgroundPixels"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.Resources>
<ImageBrush x:Key="ib" ImageSource="ges.png"/>
</Window.Resources>
<Canvas x:Name="canvas" MouseLeftButtonDown="CanvasMouseLeftButtonDown"
MouseLeftButtonUp="CanvasMouseLeftButtonUp"
MouseMove="CanvasMouseMove">
<Canvas Width="780" Height="370" >
<Canvas.Background>
<VisualBrush TileMode="Tile" Stretch="Uniform" Viewport="20,20,20,20" ViewportUnits="Absolute">
<VisualBrush.Visual>
<Rectangle Width="20" Height="20" Fill="White" Stroke="Black" StrokeThickness="0.2"/>
</VisualBrush.Visual>
</VisualBrush>
</Canvas.Background>
</Canvas>
<Image x:Name="img2" Source="ges.png" Margin="10,370 " Width="50" Height="50" />
</Canvas>
</Window>
MainWindow.xaml.cs:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var bm = new BitmapImage(new Uri(@"\\ ...\BackgroundPixels\ges.png"));
var im = new Image { Source=bm};
im.Width=50;
im.Height=50;
im.Opacity=0.5;
Canvas.SetLeft(im,10);
Canvas.SetTop(im,10);
canvas.Children.Add(im);
}
private Image draggedImage;
private Point mousePosition;
private void CanvasMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
var image = e.Source as Image;
if (image != null && canvas.CaptureMouse())
{
mousePosition = e.GetPosition(canvas);
draggedImage = image;
Panel.SetZIndex(draggedImage, 1); ![166208-1.gif][1]
}
}
private void CanvasMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if (draggedImage != null)
{
canvas.ReleaseMouseCapture();
Panel.SetZIndex(draggedImage, 0);
draggedImage = null;
}
}
private void CanvasMouseMove(object sender, MouseEventArgs e)
{
if (draggedImage != null)
{
var position = e.GetPosition(canvas);
var offset = position - mousePosition;
mousePosition = position;
Canvas.SetLeft(draggedImage, Canvas.GetLeft(draggedImage) + offset.X);
Canvas.SetTop(draggedImage, Canvas.GetTop(draggedImage) + offset.Y);
}
}
}
The result:
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our [documentation][5] to enable e-mail notifications if you want to receive the related email notification for this thread.
[5]: https://learn.microsoft.com/en-us/answers/articles/67444/email-notifications.html