Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PointerPressed not working on left click

Creating Metro (Microsoft UI) app for Windows 8 on WPF+C#, I met difficulty with PointerPressed event on a button. Event doesn't happen when i perform left-click (by mouse), but it happens in case with right-click or tap. So what's wrong with that event? for example

 <Button x:Name="Somebutton"  Width="100" Height="100"
PointerPressed="Somebutton_PointerPressed"/>
like image 364
xkillah Avatar asked Feb 08 '13 06:02

xkillah


2 Answers

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); 
like image 86
xkillah Avatar answered Oct 28 '22 10:10

xkillah


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.

like image 3
Pete Baughman Avatar answered Oct 28 '22 10:10

Pete Baughman