WPF実装コントロールドラッグ
1679 ワード
コントロールドラッグを実現する基本原理は、マウスの位置をキャプチャすると同時に、マウスボタンの押下、解放に基づいてコントロールの移動の幅とタイミングを決定することである.簡単な例:GridにButtonがあり、マウスイベントによってButtonのMarginプロパティを改編し、GridにおけるButtonの相対位置を変更します.
Buttonコントロールに3つのイベントをバインド:マウスの押下、マウスの移動、マウスの解放
変数+マウス押下イベントの定義
マウス移動イベント
マウスによるイベントの解放
"gd">
Buttonコントロールに3つのイベントをバインド:マウスの押下、マウスの移動、マウスの解放
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();
}