WPF實現(xiàn)控件拖動的示例代碼
更新時間:2018年08月12日 14:17:40 作者:ludewig
這篇文章主要介紹了WPF實現(xiàn)控件拖動的示例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
實現(xiàn)控件拖動的基本原理是對鼠標位置的捕獲,同時根據(jù)鼠標按鍵的按下、釋放確定控件移動的幅度和時機。
簡單示例:
在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();
}
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:
相關(guān)文章
C#實現(xiàn)按照指定長度在數(shù)字前補0方法小結(jié)
這篇文章主要介紹了C#實現(xiàn)按照指定長度在數(shù)字前補0方法,實例總結(jié)了兩個常用的數(shù)字補0的技巧,非常具有實用價值,需要的朋友可以參考下2015-04-04
C#調(diào)用執(zhí)行外部程序的實現(xiàn)方法
這篇文章主要介紹了C#調(diào)用執(zhí)行外部程序的實現(xiàn)方法,涉及C#進程調(diào)用的相關(guān)使用技巧,非常簡單實用,需要的朋友可以參考下2015-04-04
c#生成excel示例sql數(shù)據(jù)庫導出excel
這篇文章主要介紹了c#操作excel的示例,里面的方法可以直接導出數(shù)據(jù)到excel,大家參考使用吧2014-01-01

