WPF中的Button.MouseMove事件始终具有状态为Released的e.LeftMouse

bvhaajcl  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(121)

我试图在WPF中的Button控件上开始拖放。我使用Button是因为我也想处理单击事件。
在XAML中添加Button并处理MouseMove事件时,e.LeftMouse始终等于MouseButtonState.Released

<Button MouseMove="Button_MouseMove"/>

字符串
在下面的处理程序实现中,异常永远不会抛出。

private void Button_MouseMove(object sender, MouseEventArgs e)
{
    if (e.LeftButton == MouseButtonState.Pressed)
        throw new Exception("It works!");
}


我注意到同样的情况也适用于我放置在Button中并试图处理MouseMove事件的任何控件。
我如何处理拖放从按钮控件或任何其他控件内的按钮在WPF?
EDIT -基于mm 8答案的解决方案
更新后的XAML是:

<Button PreviewMouseDown="Button_PreviewMouseDown"
        PreviewMouseUp="Button_PreviewMouseUp"
        PreviewMouseMove="Button_PreviewMouseMove">
</Button>


更新后的处理程序代码:

Point startPosition;
double delta = 10;
private void Button_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
    e.Handled = true;
    startPosition = e.GetPosition(this);
}

private void Button_PreviewMouseUp(object sender, MouseButtonEventArgs e)
{
    Point currentPosition = e.GetPosition(this);

    if ((currentPosition - startPosition).Length < delta)
        throw new Exception("MouseClick");
}

private void Button_PreviewMouseMove(object sender, MouseEventArgs e)
{
    Point currentPosition = e.GetPosition(this);
    double currentDelta = (currentPosition - startPosition).Length;

    if (e.LeftButton == MouseButtonState.Pressed && currentDelta >= delta)
        throw new Exception("DragAndDrop");
}

tct7dpnv

tct7dpnv1#

你可以处理PreviewMouseDown事件而不是Click

private void Button_Click(object sender, MouseButtonEventArgs e)
{
    //handle click here...

    e.Handled = true;
}

字符串

XAML:

<Button PreviewMouseDown="Button_Click" MouseMove="Button_MouseMove"/>

相关问题