中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

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
华蓥市| 博爱县| 房产| 白水县| 周至县| 岳西县| 清远市| 宁安市| 政和县| 余干县| 北宁市| 浦县| 石台县| 阿克苏市| 灵川县| 萨迦县| 北海市| 南乐县| 郑州市| 边坝县| 玉环县| 淮安市| 六枝特区| 涞水县| 时尚| 德钦县| 胶州市| 台前县| 台江县| 榆林市| 康马县| 南澳县| 盐池县| 米脂县| 琼中| 双江| 朔州市| 兴仁县| 长武县| 南康市| 庆城县|