WPF實現控件拖動的示例代碼
更新時間:2018年08月12日 14:17:40 作者:ludewig
這篇文章主要介紹了WPF實現控件拖動的示例代碼,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
實現控件拖動的基本原理是對鼠標位置的捕獲,同時根據鼠標按鍵的按下、釋放確定控件移動的幅度和時機。
簡單示例:
在Grid中有一個Button,通過鼠標事件改編Button的Margin屬性,從而改變Button在Grid中的相對位置。
<Grid Name="gd"> <Button Width=90 Height=30 Name="btn">button</Button> </Grid>
為Button控件綁定三個事件:鼠標按下、鼠標移動、鼠標釋放
public SystemMap()
{
InitializeComponent();
btn.MouseLeftButtonDown += btn_MouseLeftButtonDown;
btn.MouseMove += btn_MouseMove;
btn.MouseLeftButtonUp += btn_MouseLeftButtonUp;
}
定義變量+鼠標按下事件
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;
}
鼠標移動事件
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);
}
}
鼠標釋放事件
void btn_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
Button tmp = (Button)sender;
tmp.ReleaseMouseCapture();
}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:

