【问题标题】:How to: Drag and Drop movement in Windows 8 apps?如何:在 Windows 8 应用程序中拖放移动?
【发布时间】:2013-08-18 21:52:11
【问题描述】:

我想制作一个简单的配对游戏来帮助更好地理解运动,其中我将拥有形状的轮廓和形状本身。将形状拖到其轮廓上并释放它以使其卡入到位。听起来很简单。我可以使用 ManipulationDelta 事件移动我的形状,但由于某种原因,我无法触发任何拖动事件(DragOver、DragEnter、Drop)。我已经阅读了这些事件,但也许我的理解存在缺陷。为了知道一个形状何时被拖到另一个形状上,我要查找什么事件?

XAML

<Canvas Name="DrawCanvas">
    <Ellipse Name="Shape1" Fill="SteelBlue" Height="200" Width="200"  ManipulationMode="All" AllowDrop="True" DragOver="Shape1_DragOver" DragEnter="Shape2_DragEnter"  Drop="Shape1_Drop"/>
    <Ellipse Name="Shape2" Height="209" Width="209" Stroke="SteelBlue" StrokeThickness="5" AllowDrop="True" Canvas.Left="594" Canvas.Top="96"  />
</Canvas>

我已经尝试过 Shape1 和 Shape2 上的 DragOver、DragEnter、Drop 事件的所有组合,但它们似乎从未触发过。这些事件不适用于形状吗?还是有可能在使用 ManipulationDelta 进行运动时它们不起作用?

谢谢,非常感谢您对此的任何帮助或指导。

【问题讨论】:

  • Windows8 中是否有 AllowDrop 属性?如果是这样,您应该将其设置为 true 以获取提及的事件。
  • 是的。在上面的示例中,我实际上为两种形状都设置了它,有一次我什至将它放在画布本身上。

标签: c# xaml drag-and-drop windows-store-apps


【解决方案1】:

答案是获取画布的边界、形状的大小及其 X、Y。从中可以得出它周围的 4 个点(topLeft、topRight、bottomLeft、bottomRight)。当一个点在操作增量事件中超出您的边界时,请将其设置为该边界。这有效地保持形状“在界限内”。

translation.X = e.Delta.Translation.X;
translation.Y = e.Delta.Translation.Y

// Since we are checking the left point subtract your shapes width from the canvas right
// bounds.  If X is greater than this set it instead to that maximum bound.
if (translation.X > (canvasright - shape.Width))
    translation.X = canvasright - shape.Width;

/// Same for top.  If Y is less than the canvas top set it instead right at the boundary.
if (translation.Y < canvastop)
    translation.Y = canvastop;

// Do the same for bottom and left

也可以使用形状中心来执行此操作,这可能会根据您实现的功能提供优势。使用 center 时,形状的顶部或底部是高度的一半,左右是宽度的一半。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-19
    • 1970-01-01
    • 1970-01-01
    • 2016-02-16
    相关资源
    最近更新 更多