Drag and drop an image in WPF

你。 提交于 2020-01-03 02:48:08

问题


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; }


回答1:


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.




回答2:


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".



来源:https://stackoverflow.com/questions/3080357/drag-and-drop-an-image-in-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!