WPF實(shí)現(xiàn)控件拖動(dòng)的示例代碼
實(shí)現(xiàn)控件拖動(dòng)的基本原理是對(duì)鼠標(biāo)位置的捕獲,同時(shí)根據(jù)鼠標(biāo)按鍵的按下、釋放確定控件移動(dòng)的幅度和時(shí)機(jī)。
簡單示例:
在Grid中有一個(gè)Button,通過鼠標(biāo)事件改編Button的Margin屬性,從而改變Button在Grid中的相對(duì)位置。
<Grid Name="gd"> <Button Width=90 Height=30 Name="btn">button</Button> </Grid>
為Button控件綁定三個(gè)事件:鼠標(biāo)按下、鼠標(biāo)移動(dòng)、鼠標(biāo)釋放
public SystemMap()
{
InitializeComponent();
btn.MouseLeftButtonDown += btn_MouseLeftButtonDown;
btn.MouseMove += btn_MouseMove;
btn.MouseLeftButtonUp += btn_MouseLeftButtonUp;
}
定義變量+鼠標(biāo)按下事件
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;
}
鼠標(biāo)移動(dòng)事件
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);
}
}
鼠標(biāo)釋放事件
void btn_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
Button tmp = (Button)sender;
tmp.ReleaseMouseCapture();
}
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C#實(shí)現(xiàn)按照指定長度在數(shù)字前補(bǔ)0方法小結(jié)
這篇文章主要介紹了C#實(shí)現(xiàn)按照指定長度在數(shù)字前補(bǔ)0方法,實(shí)例總結(jié)了兩個(gè)常用的數(shù)字補(bǔ)0的技巧,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2015-04-04
C#中通過API實(shí)現(xiàn)的打印類 實(shí)例代碼
這篇文章介紹了,C#中通過API實(shí)現(xiàn)的打印類 實(shí)例代碼,有需要的朋友可以參考一下2013-08-08
C#提高編程能力的50個(gè)要點(diǎn)總結(jié)
這篇文章主要介紹了C#提高編程能力的50個(gè)要點(diǎn),較為詳細(xì)的總結(jié)分析了C#程序設(shè)計(jì)中常見的注意事項(xiàng)與編程技巧,需要的朋友可以參考下2016-02-02
C#調(diào)用執(zhí)行外部程序的實(shí)現(xiàn)方法
這篇文章主要介紹了C#調(diào)用執(zhí)行外部程序的實(shí)現(xiàn)方法,涉及C#進(jìn)程調(diào)用的相關(guān)使用技巧,非常簡單實(shí)用,需要的朋友可以參考下2015-04-04
c#生成excel示例sql數(shù)據(jù)庫導(dǎo)出excel
這篇文章主要介紹了c#操作excel的示例,里面的方法可以直接導(dǎo)出數(shù)據(jù)到excel,大家參考使用吧2014-01-01

