简体   繁体   中英

Drag and drop an image in WPF

I'm trying to drag and drop an image from one spot on the canvas to another (should be relatively simple), but can't figure it out. The image which I want to move has the following XAML:

<Image Height="28" HorizontalAlignment="Left" Margin="842,332,0,0" Name="cityImage" Stretch="Fill" VerticalAlignment="Top" Width="42" Source="/Settlers;component/Images/city.png" MouseLeftButtonDown="cityImage_MouseLeftButtonDown" MouseMove="cityImage_MouseMove" MouseLeftButtonUp="cityImage_MouseLeftButtonUp"/>

The code is as follows:

bool isDragging = false; Point initMousePos; private void cityImage_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) {
isDragging = true;
initMousePos = e.GetPosition(theGrid); } private void cityImage_MouseMove(object sender, MouseEventArgs e) {
if (isDragging)
{
    Image image = sender as Image;
    Canvas.SetTop(image, initMousePos.X);
    Canvas.SetLeft(image, initMousePos.Y);
    image.Visibility = System.Windows.Visibility.Visible;
} }

private void cityImage_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) { isDragging = false; }

What I do to accomplish what you want is to use

System.Windows.Controls.Primitives.Thumb 

as the Root of a UserControl and set the ControlTemplate to display an image (within a border but it should work without as well), something like:

<Thumb Name="myRoot" DragDelta="MyRootDragDelta">
  <Thumb.Template>
    <ControlTemplate>
      <Image ... >
      ... see below ...
      </Image>
    </ControlTemplate>
  </Thumb.Template>
</Thumb>

Also, I bind the Source of the Image to a property of the class:

<Image.Source>
  <Binding Path="ImageSource" RelativeSource=
                 {RelativeSource FindAncestor,
                  AncestorType=my:MyImageControl, AncestorLevel=1}" />
</Image.Source>

The UserControl has a named TranslateTransform (let's say translateTransform ) whose properties X and Y are to be set in the DragDelta event handler:

private void MyRootDragDelta(object sender, DragDeltaEventArgs e) 
{
  translateTransform.X += e.HorizontalChange;
  translateTransform.Y += e.VerticalChange;
}

Don't forget to add:

public ImageSource ImageSource { get; set; }

Hope this helps. If anything's unclear feel free to ask further.

You want to set the Left and Top properties of the Canvas to something other than the initial position. In the MouseMove handler you have to get the position relative to the parent. Also; make sure the parent element is a canvas and not a grid. You have a pretty big left and top margin on the image, aswell as a control with the variable name "theGrid".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM