WPF 自由拖拽控件

为了演示,布局文件很简单,只是放了我一个自己做的自定义虚拟键盘控件,也可以放其他各种控件,例如button….

 <Grid >     
      <KeyBoard:Keyboard Name="keyb" HorizontalAlignment="Left" Height="196" Margin="68,75,0,0" VerticalAlignment="Top" Width="588" MouseLeftButtonDown="keyb_MouseLeftButtonDown" MouseLeftButtonUp="keyb_MouseLeftButtonUp" MouseMove="keyb_MouseMove"/>
    Grid>

为此控件加上MouseLeftButtonDown、MouseLeftButtonUp、MouseMove事件
后天代码书写:

public MainWindow()
        {
            InitializeComponent();

            keyb.MouseLeftButtonDown += keyb_MouseLeftButtonDown;
            keyb.MouseMove += keyb_MouseMove;
            keyb.MouseLeftButtonUp += keyb_MouseLeftButtonUp;

        }
 Point point = new Point();
 private void keyb_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {

            point = e.GetPosition(null);
            keyb.CaptureMouse();
            keyb.Cursor = Cursors.Hand;
        }

        private void keyb_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            keyb.ReleaseMouseCapture();
        }

        private void keyb_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {

                double dx = e.GetPosition(null).X - point .X + keyb.Margin.Left;
                double dy = e.GetPosition(null).Y - point .Y + keyb.Margin.Top;
                keyb.Margin = new Thickness(dx, dy, 0, 0);
                point = e.GetPosition(null);
            }
        }

一定要注意控件最好大一点 ,鼠标放在其内才能拖动,不然会出现未必想要的结果。

你可能感兴趣的:(WPF)