标签:
public class MoveThumb :Thumb { public MoveThumb() { this.DragDelta += MoveThumb_DragDelta; } public void MoveThumb_DragDelta(object sender, DragDeltaEventArgs e) { Thumb myThumb = (Thumb )sender; double nTop = Canvas .GetTop(myThumb) + e.VerticalChange; double nLeft = Canvas .GetLeft(myThumb) + e.HorizontalChange; Canvas.SetTop(myThumb, nTop); Canvas.SetLeft(myThumb, nLeft); } }
前台
<Window.Resources> <ControlTemplate x :Key="rec"> <Rectangle Fill ="Gray" Width="70" Height="50"></ Rectangle> </ControlTemplate> <ControlTemplate x :Key="ell"> <Ellipse Fill ="Gray" Width="70" Height="70"></ Ellipse> </ControlTemplate> </Window.Resources > <Grid > <Canvas Background ="AliceBlue" HorizontalAlignment="Left" Height="412" Margin="10,10,0,0" VerticalAlignment="Top" Width="522"> <local: MoveThumb Canvas.Left="50" Canvas.Top="50" Template="{StaticResource rec}"></local: MoveThumb> <local: MoveThumb Canvas.Left="140" Canvas.Top="50" Template="{StaticResource ell}"></local: MoveThumb> <local: MoveThumb Canvas.Left="250" Canvas.Top="50" Template="{StaticResource ell}"></local: MoveThumb> </Canvas> </Grid >
<ContentControl Canvas.Left ="50" Canvas.Top="50" Template="{StaticResource thumbItemTemplate}"> <Ellipse Width ="50" Height="50" Fill="OrangeRed" IsHitTestVisible="False"></ Ellipse> </ContentControl>
<ControlTemplate x :Key="rawThumbTemplate" TargetType="Thumb"> <Rectangle Fill ="Transparent"></Rectangle> </ControlTemplate> <ControlTemplate x :Key="thumbItemTemplate" TargetType="ContentControl"> <Grid DataContext ="{Binding RelativeSource ={RelativeSource TemplatedParent}}"> <!--这里的放置顺序还是有讲究的--> <local: MoveThumb Template="{ StaticResource rawThumbTemplate}" Cursor="SizeAll"></ local:MoveThumb > <ContentPresenter Content ="{TemplateBinding Content}"></ContentPresenter> </Grid> </ControlTemplate>
public void MoveThumb_DragDelta( object sender, DragDeltaEventArgs e) { Control item = this.DataContext as Control; if(item!= null) { double left = Canvas.GetLeft(item); double top = Canvas.GetTop(item); Canvas.SetTop(item,top+e.VerticalChange); Canvas.SetLeft(item,left+e.HorizontalChange); } }
标签:
原文地址:http://www.cnblogs.com/JasonShenW/p/4937344.html