WPF實(shí)現(xiàn)控件拖動的示例代碼
更新時間:2018年08月12日 14:17:40 作者:ludewig
這篇文章主要介紹了WPF實(shí)現(xiàn)控件拖動的示例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
實(shí)現(xiàn)控件拖動的基本原理是對鼠標(biāo)位置的捕獲,同時根據(jù)鼠標(biāo)按鍵的按下、釋放確定控件移動的幅度和時機(jī)。
簡單示例:
在Grid中有一個Button,通過鼠標(biāo)事件改編Button的Margin屬性,從而改變Button在Grid中的相對位置。
<Grid Name="gd"> <Button Width=90 Height=30 Name="btn">button</Button> </Grid>
為Button控件綁定三個事件:鼠標(biāo)按下、鼠標(biāo)移動、鼠標(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)移動事件
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)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:
相關(guān)文章
C#實(shí)現(xiàn)拷貝文件的9種方法小結(jié)
最近遇一個問題,一個程序調(diào)用另一個程序的文件,結(jié)果另一個程序的文件被占用,使用不了文件,這時候的解決方案就是把另一個程序的文件拷貝到當(dāng)前程序就可以了,本文介紹用C#拷貝文件的多種方式,需要的朋友可以參考下2024-04-04

