鼠标单击并拖动事件 WPF

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17441672/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 09:08:18  来源:igfitidea点击:

Mouse click and drag Event WPF

wpfeventsclickdrag

提问by Ji yong

I am developing an analog clock picker control. The user is able to click on the minute or hour hand and drag to turn the needle to select the specific time. I was wondering how to detect such a click and drag event.

我正在开发一个模拟时钟选择器控件。用户可以单击分针或时针并拖动以转动指针以选择特定时间。我想知道如何检测这样的点击和拖动事件。

I tried using MouseLeftButtonDown + MouseMove but I cannot get it to work as MouseMove is always trigger when the mousemove happen despite me using a flag. Is there any easier way?

我尝试使用 MouseLeftButtonDown + MouseMove 但我无法让它工作,因为尽管我使用了标志,但在发生 mousemove 时总是触发 MouseMove。有没有更简单的方法?

public bool dragAction = false;

private void minuteHand_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    dragAction = true;
    minuteHand_MouseMove(this.minuteHand, e);
}

private void minuteHand_MouseMove(object sender, MouseEventArgs e)
{
    if (dragAction == true)
    {
       //my code: moving the needle
    }
 }

 private void minuteHand_MouseLeftButtonUp(object sender, MouseEventArgs e)
 {
    dragAction = false;
 }

回答by George TG

I think this is the easiest and most straightforward way :

我认为这是最简单和最直接的方法:

 private void Window_MouseMove(object sender, MouseEventArgs e) {
     if (e.LeftButton == MouseButtonState.Pressed) {
        this.DragMove();
     }
 }

回答by deafjeff

You can make things easier and need not handle mouse down / up :

你可以让事情变得更简单,不需要处理鼠标向下/向上:

private void minuteHand_MouseMove(object sender, MouseEventArgs e)
{
    if (Mouse.LeftButton == MouseButtonState.Pressed)
    {
        //my code: moving the needle
    }
 }    

回答by Nick Prozee

public bool dragAction = false;

private void minuteHand_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    dragAction = true;
    minuteHand_MouseMove(this.minuteHand, e);
}

private void minuteHand_MouseMove(object sender, MouseEventArgs e)
{
    if (dragAction == true)
    {
       this.DragMove();
    }
 }

 private void minuteHand_MouseLeftButtonUp(object sender, MouseEventArgs e)
 {
    dragAction = false;
 }

does the trick

有诀窍