WPF實(shí)現(xiàn)控件拖動(dòng)的示例代碼
實(shí)現(xiàn)控件拖動(dòng)的基本原理是對(duì)鼠標(biāo)位置的捕獲,同時(shí)根據(jù)鼠標(biāo)按鍵的按下、釋放確定控件移動(dòng)的幅度和時(shí)機(jī)。
簡(jiǎn)單示例:
在Grid中有一個(gè)Button,通過(guò)鼠標(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();
}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C#實(shí)現(xiàn)拷貝文件的9種方法小結(jié)
最近遇一個(gè)問(wèn)題,一個(gè)程序調(diào)用另一個(gè)程序的文件,結(jié)果另一個(gè)程序的文件被占用,使用不了文件,這時(shí)候的解決方案就是把另一個(gè)程序的文件拷貝到當(dāng)前程序就可以了,本文介紹用C#拷貝文件的多種方式,需要的朋友可以參考下2024-04-04
C#使用foreach語(yǔ)句簡(jiǎn)單遍歷數(shù)組的方法
這篇文章主要介紹了C#使用foreach語(yǔ)句簡(jiǎn)單遍歷數(shù)組的方法,涉及C#中foreach語(yǔ)句的使用技巧,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2015-04-04
c#語(yǔ)言使用Unity粒子系統(tǒng)制作手雷爆炸
這篇文章主要為大家介紹了Unity的粒子系統(tǒng)由粒子發(fā)射器、粒子動(dòng)畫(huà)器、粒子渲染器組成,通過(guò)使用一或兩個(gè)紋理多次繪制,創(chuàng)造一個(gè)混沌的效果,通過(guò)復(fù)習(xí)粒子系統(tǒng)做一個(gè)手雷和實(shí)彈投擲現(xiàn)場(chǎng)2022-04-04

