PointerPressed not working on left click

佐手、 提交于 2019-12-03 22:59:06

The solution is pretty simple: these events have to be handled not through XAML but thorugh AddHandler method.

SomeButton.AddHandler(PointerPressedEvent, 
new PointerEventHandler(SomeButton_PointerPressed), true); 

I have encountered this problem, but was not able to use the accepted answer because my buttons were created dynamically by an ItemsControl, and there was no good place to call AddHandler from.

Instead, I sub-classed Windows.UI.Xaml.Controls.Button:

public sealed class PressAndHoldButton : Button
{
    public event EventHandler PointerPressPreview = delegate { };

    protected override void OnPointerPressed(PointerRoutedEventArgs e)
    {
        PointerPressPreview(this, EventArgs.Empty);
        base.OnPointerPressed(e);
    }
}

Now, the consuming control can bind to PointerPressPreview instead of PointerPressed

<local:PressAndHoldButton
    x:Name="Somebutton"
    Width="100" 
    Height="100"
    PointerPressPreview="Somebutton_PointerPressed"/>

If you want, you can stuff some additional logic in the overridden OnPointerPressed method so that it only fires the event on left-click, or right-click. Whatever you want.

FWIW, I've been facing the same issue and solved it by adding the event handler to some other control (but a button).

In my case I had a Button wrapped around a SymbolIcon like so:

<Button PointerPressed="OnTempoPressed" PointerReleased="OnTempoReleased">
  <SymbolIcon Symbol="Add" />
</Button>

What I did I just removed the Button wrap and added the handlers to the SymbolIcon itself everything works now:

<SymbolIcon Symbol="Add"
  PointerPressed="OnTempoPressed" PointerReleased="OnTempoReleased"/>

If you are you are working with a Button control then try to attach event with "Click" event.

Please note that Button control internally consider and handles PointerPressed, MouseLeftButtonDown, MouseLeftButtonUp and raise Click event. Generally Button control wont allow PointerPressed, MouseLeftButtonDown, MouseLeftButtonUp event to bubble up and fire.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!