亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

WPF中鼠標拖拽事件怎么封裝

wpf
小億
84
2024-03-08 15:01:25
欄目: 編程語言

在WPF中,可以使用MouseLeftButtonDownMouseLeftButtonUpMouseMove事件來實現鼠標拖拽功能的封裝。以下是一個簡單的示例:

public class DraggableControl : Control
{
    private bool isDragging = false;

    public DraggableControl()
    {
        this.MouseLeftButtonDown += DraggableControl_MouseLeftButtonDown;
        this.MouseLeftButtonUp += DraggableControl_MouseLeftButtonUp;
        this.MouseMove += DraggableControl_MouseMove;
    }

    private void DraggableControl_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        if (e.LeftButton == MouseButtonState.Pressed)
        {
            isDragging = true;
            this.CaptureMouse();
        }
    }

    private void DraggableControl_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
        if (isDragging)
        {
            isDragging = false;
            this.ReleaseMouseCapture();
        }
    }

    private void DraggableControl_MouseMove(object sender, MouseEventArgs e)
    {
        if (isDragging)
        {
            Point currentPosition = e.GetPosition(this.Parent as UIElement);
            Canvas.SetLeft(this, currentPosition.X - (this.ActualWidth / 2));
            Canvas.SetTop(this, currentPosition.Y - (this.ActualHeight / 2));
        }
    }
}

使用這個DraggableControl類可以方便地給任意的WPF控件添加鼠標拖拽功能。只需要在XAML文件中聲明DraggableControl替代原本的控件即可。

0
双鸭山市| 万全县| 曲沃县| 中宁县| 福清市| 永城市| 武乡县| 上杭县| 鲁山县| 大理市| 治多县| 习水县| 金昌市| 图木舒克市| 洱源县| 遂平县| 缙云县| 恭城| 简阳市| 兴宁市| 东乡县| 大洼县| 温泉县| 光泽县| 务川| 洛阳市| 米脂县| 永安市| 舞钢市| 安顺市| 新河县| 内丘县| 娄烦县| 清丰县| 浮梁县| 镇安县| 平南县| 确山县| 社旗县| 将乐县| 乌恰县|