拖放在WPF图像 [英] Drag and drop an image in WPF

查看:203
本文介绍了拖放在WPF图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将它从一个地方画布到另一个(应该是比较简单)上放置的图像,但无法弄清楚。我想移动的图像有以下XAML:

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



私人无效cityImage_MouseLeftButtonUp(对象发件人,MouseButtonEventArgs E){
isDragging = FALSE; }

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 

作为UserControl的根,并设置控件模板显示图像(边界内,但它应该不会同时工作),是这样的:

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>

在用户控件有一个名为 TranslateTransform (假设 translateTransform ),其属性 X 是在 DragDelta 事件处理程序进行设置:

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

不要忘了加一句:

public ImageSource ImageSource { get; set; }

希望这有助于如果有什么不清楚随意问。进一步。

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

这篇关于拖放在WPF图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆