Objective To achieve all the controls in the form, you can drag C # The layout code is as follows:
<Window x:Class="DragLabel.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525" MouseMove="Window_MouseMove" MouseUp="Window_MouseUp"> <Grid> <Canvas Height="227" HorizontalAlignment="Left" Margin="20,31,0,0" Name="canvas1" VerticalAlignment="Top" Width="447"> <Label Canvas.Left="84" Canvas.Top="120" Content="Label" Height="28" Name="label1" MouseDown="label1_MouseDown" /> <StackPanel Canvas.Left="242" Canvas.Top="96" Height="100" Name="stackPanel1" Width="142" MouseDown="stackPanel1_MouseDown"> <Label Content="Label" Height="28" Name="label2" /> <Label Content="Label" Height="28" Name="label3" /> </StackPanel> </Canvas> </Grid> </Window>
C # The implementation code is as follows:
Using System; using System. collections. generic; using System. linq; using System. text; using System. windows; using System. windows. controls; using System. windows. data; using System. windows. documents; using System. windows. input; using System. windows. media; using System. windows. media. imaging; using System. windows. navigation; using System. windows. shapes; namespace DragLabel {// <summary> // MainWindow. interaction logic of xaml // </summary> public partial class MainWindow: Window {bool IsMouseDown = false; Point mousePoint; object mouseCtrl = null; public MainWindow () {InitializeComponent ();} private void Window_MouseMove (object sender, MouseEventArgs e) {if (IsMouseDown) {if (e. leftButton = MouseButtonState. pressed) {Point theMousePoint = e. getPosition (this. canvas1); Canvas. setLeft (UIElement) mouseCtrl, theMousePoint. x-(mousePoint. x-Canvas. getLeft (UIElement) mouseCtrl); Canvas. setTop (UIElement) mouseCtrl, theMousePoint. y-(mousePoint. y-Canvas. getTop (UIElement) mouseCtrl); mousePoint = theMousePoint ;}} private void Window_MouseUp (object sender, MouseButtonEventArgs e) {if (IsMouseDown) {IsMouseDown = false ;}} private void label=mousedown (object sender, MouseButtonEventArgs e) {if (e. leftButton = MouseButtonState. pressed) {IsMouseDown = true; mousePoint = e. getPosition (this. canvas1); mouseCtrl = sender;} private void stackpanel?mousedown (object sender, MouseButtonEventArgs e) {if (e. leftButton = MouseButtonState. pressed) {IsMouseDown = true; mousePoint = e. getPosition (this. canvas1); mouseCtrl = sender ;}}}}