c# - 在 WPF 中拖放图像

标签 c# wpf drag-and-drop

我试图将图像从 Canvas 上的一个点拖放到另一个点(应该相对简单),但无法弄清楚。我要移动的图像具有以下 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"/>

代码如下:

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;

最佳答案

我为了完成你想要的就是用

System.Windows.Controls.Primitives.Thumb 

作为 UserControl 的根并设置 ControlTemplate 以显示图像(在边框内但它也应该在没有边框的情况下工作),例如:

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

此外,我将图像的来源绑定(bind)到类的属性:

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

UserControl 有一个命名的TranslateTransform(比方说translateTransform),它的属性XY 是在 DragDelta 事件处理程序中设置:

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

不要忘记添加:

public ImageSource ImageSource { get; set; }

希望这对您有所帮助。如果有任何不清楚的地方,请随时进一步询问。

关于c# - 在 WPF 中拖放图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3080357/

相关文章:

c# - 如何将焦点设置到 datagridview 中的特定单元格?

c# - 静态媒体元素

wpf - 网格 SharedSizeGroup - 列在无限循环中弹跳、调整大小

WPF<->XNA - 如何结合这两种技术?

Flutter:使用 Grid 拖放

python - PyQt 拖放 - 没有任何反应

c# - MVC Ajax.ActionLink 找不到 POST 方法

c# - 匿名 StreamReader 会自动关闭吗?

c# - 动态字符串 x 静态字符串

java - 在不同嵌套级别的 JTree 中删除节点