實現控件拖動的基本原理是對鼠標位置的捕獲,同時根據鼠標按鍵的按下、釋放確定控件移動的幅度和時機。
簡單示例:
在Grid中有一個Button,通過鼠標事件改編Button的Margin屬性,從而改變Button在Grid中的相對位置。
1
2
3
|
< Grid Name = "gd" > < Button Width = 90 Height = 30 Name = "btn" >button</ Button > </ Grid > |
為Button控件綁定三個事件:鼠標按下、鼠標移動、鼠標釋放
1
2
3
4
5
6
7
|
public SystemMap() { InitializeComponent(); btn.MouseLeftButtonDown += btn_MouseLeftButtonDown; btn.MouseMove += btn_MouseMove; btn.MouseLeftButtonUp += btn_MouseLeftButtonUp; } |
定義變量+鼠標按下事件
1
2
3
4
5
6
7
8
|
Point pos = new Point(); void btn_MouseLeftButtonDown( object sender, MouseButtonEventArgs e) { Button tmp = (Button)sender; pos = e.GetPosition( null ); tmp.CaptureMouse(); tmp.Cursor = Cursors.Hand; } |
鼠標移動事件
1
2
3
4
5
6
7
8
9
10
11
|
void btn_MouseMove( object sender, MouseEventArgs e) { if (e.LeftButton==MouseButtonState.Pressed) { Button tmp = (Button)sender; double dx = e.GetPosition( null ).X - pos.X + tmp.Margin.Left; double dy = e.GetPosition( null ).Y - pos.Y + tmp.Margin.Top; tmp.Margin = new Thickness(dx, dy, 0, 0); pos = e.GetPosition( null ); } } |
鼠標釋放事件
1
2
3
4
5
|
void btn_MouseLeftButtonUp( object sender, MouseButtonEventArgs e) { Button tmp = (Button)sender; tmp.ReleaseMouseCapture(); } |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/lordwish/article/details/51823637