【C#/WPF】用Thumb做可拖拽的UI控件

原文: 【C#/WPF】用Thumb做可拖拽的UI控件

需求:简单的可拖拽的图片

使用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来定位,否则无法拖动!

重要的参考:

猜你喜欢

转载自www.cnblogs.com/lonelyxmas/p/12741788.html