PointerPressed事件在左键单击时不起作用。

21

在使用WPF+C#为Windows 8创建Metro (Microsoft UI)应用程序时,我在按钮的PointerPressed事件上遇到了困难。当我用鼠标左键单击时,事件不会发生,但是如果使用右键单击或触摸,则会发生。那么这个事件出了什么问题呢?

 <Button x:Name="Somebutton"  Width="100" Height="100"
PointerPressed="Somebutton_PointerPressed"/>

@ACB 这只是一个简单的按钮。我附上了代码,以便帮助您。 - xkillah
4个回答

44
解决方案相当简单:这些事件不应该通过XAML处理,而是应该通过AddHandler方法处理。
SomeButton.AddHandler(PointerPressedEvent, 
new PointerEventHandler(SomeButton_PointerPressed), true); 

4
很抱歉,如果这个问题很蠢,但是为什么在XAML中声明后它不能工作的原因是什么? - dcdroid
7
因为在XAML中无法将bool类型的参数“handledEventsToo”设置为true。但是这个参数是很重要的细节,因为如果没有它,事件会在Button内部被处理,并且“忽略”你的处理程序。 - xkillah
微软的世界有多奇怪和困难啊...即使是简单的事情也不容易。 - Sergey Orlov
我在UWP中遇到了同样的问题。无法找到像你建议的那样添加事件的方法。尝试这样做时,我会收到一个错误:“值不在预期范围内”。 - Shimmy Weitzhandler
非常感谢,这个帮了我大忙。我正在开发一个UWP项目。 - AntiqTech

4

我遇到了这个问题,但是无法使用已接受的答案,因为我的按钮是由ItemsControl动态创建的,而且没有好的地方调用AddHandler。

相反,我对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);
    }
}

现在,消费控件可以绑定到PointerPressPreview而不是PointerPressed。
<local:PressAndHoldButton
    x:Name="Somebutton"
    Width="100" 
    Height="100"
    PointerPressPreview="Somebutton_PointerPressed"/>

如果您想的话,可以在重写的OnPointerPressed方法中添加一些额外的逻辑,使其仅在左键单击或右键单击时触发事件。您可以按照自己的意愿进行设置。

0

顺便说一句,我也遇到了同样的问题,并通过将事件处理程序添加到其他控件(但是按钮)来解决它。

在我的情况下,我有一个Button包装在SymbolIcon周围,如下所示:

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

我所做的就是移除了Button包装,并用ViewBox替换它,然后将处理程序添加到ViewBox本身,现在一切都正常:
<Viewbox PointerPressed="OnTempoPressed" PointerReleased="OnTempoReleased">
    <SymbolIcon Symbol="Add"/>
</Viewbox>

请注意,您会失去按钮的视觉效果(例如悬停等),但对我来说这不是问题。我认为您可以从默认样式重新应用它们。

-1

如果您正在使用Button控件,则尝试将事件附加到“Click”事件。

请注意,Button控件在内部考虑并处理PointerPressed、MouseLeftButtonDown、MouseLeftButtonUp事件,并引发Click事件。通常,Button控件不允许PointerPressed、MouseLeftButtonDown、MouseLeftButtonUp事件冒泡并触发。


3
不,我需要精确的PointerPressed。差异在这里描述(https://dev59.com/7GYr5IYBdhLWcg3w499-)。 - xkillah
请注意,按钮控件在内部考虑和处理PointerPressed、MouseLeftButtonDown、MouseLeftButtonUp事件,并引发Click事件。通常情况下,按钮控件不允许PointerPressed、MouseLeftButtonDown、MouseLeftButtonUp事件冒泡并触发。 - Somnath
2
是的,对于旧的桌面 Windows 应用程序确实是这样的,而对于 Metro 应用程序,由于另一个 UIElement 类,没有 MouseLeftButtonUp、MouseLeftButtonDown。UIElement class - xkillah

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接