需求:简单的可拖拽的图片
使用System.Windows.Controls.Primitives.Thumb类
前台:
<Canvas x:Name="g">
<Thumb Canvas.Left="10" Canvas.Top="20" Canvas.ZIndex="99" DragDelta="Thumb_DragDelta">
<Thumb.Template>
<ControlTemplate>
<Image Width="60" Height="60" Source="你的图片路径"/>
</ControlTemplate>
</Thumb.Template>
</Thumb>
</Canvas>
后台:
private void Thumb_DragDelta(object sender, System.Windows.Controls.Primitives.DragDeltaEventArgs e)
{
UIElement thumb = e.Source as UIElement;
// 防止Thumb控件被拖出容器。
// if (nTop <= 0)
// nTop = 0;
// if (nTop >= (g.Height - myThumb.Height))
// nTop = g.Height - myThumb.Height;
// if (nLeft <= 0)
// nLeft = 0;
// if (nLeft >= (g.Width - myThumb.Width))
// nLeft = g.Width - myThumb.Width;
// Canvas.SetTop(myThumb, nTop);
// Canvas.SetLeft(myThumb, nLeft);
// tt.Text = "Top:" + nTop.ToString() + "\nLeft:" + nLeft.ToString();
Canvas.SetLeft(thumb, Canvas.GetLeft(thumb) + e.HorizontalChange);
Canvas.SetTop(thumb, Canvas.GetTop(thumb) + e.VerticalChange);
}
坑点:
- Thumb必须是一个Canvas的子类,因为它依赖该Canvas来定位。
- Thumb必须协商Canvas.Left和Canvas.Top,因为它依赖该Vanvas来定位,否则无法拖动!
重要的参考:
- https://wpf.2000things.com/2012/12/19/715-using-the-thumb-control-to-drag-objects-on-a-canvas/
- https://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.thumb(v=vs.110).aspx
原文地址:https://www.cnblogs.com/lonelyxmas/p/9473503.html
时间: 2024-11-16 17:25:06