在使用WPF+C#为Windows 8创建Metro (Microsoft UI)应用程序时,我在按钮的PointerPressed事件上遇到了困难。当我用鼠标左键单击时,事件不会发生,但是如果使用右键单击或触摸,则会发生。那么这个事件出了什么问题呢?
<Button x:Name="Somebutton" Width="100" Height="100"
PointerPressed="Somebutton_PointerPressed"/>
在使用WPF+C#为Windows 8创建Metro (Microsoft UI)应用程序时,我在按钮的PointerPressed事件上遇到了困难。当我用鼠标左键单击时,事件不会发生,但是如果使用右键单击或触摸,则会发生。那么这个事件出了什么问题呢?
<Button x:Name="Somebutton" Width="100" Height="100"
PointerPressed="Somebutton_PointerPressed"/>
SomeButton.AddHandler(PointerPressedEvent,
new PointerEventHandler(SomeButton_PointerPressed), true);
我遇到了这个问题,但是无法使用已接受的答案,因为我的按钮是由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);
}
}
<local:PressAndHoldButton
x:Name="Somebutton"
Width="100"
Height="100"
PointerPressPreview="Somebutton_PointerPressed"/>
顺便说一句,我也遇到了同样的问题,并通过将事件处理程序添加到其他控件(但是按钮)来解决它。
在我的情况下,我有一个Button
包装在SymbolIcon
周围,如下所示:
<Button PointerPressed="OnTempoPressed" PointerReleased="OnTempoReleased">
<SymbolIcon Symbol="Add" />
</Button>
Button
包装,并用ViewBox
替换它,然后将处理程序添加到ViewBox
本身,现在一切都正常:<Viewbox PointerPressed="OnTempoPressed" PointerReleased="OnTempoReleased">
<SymbolIcon Symbol="Add"/>
</Viewbox>
按钮
的视觉效果(例如悬停等),但对我来说这不是问题。我认为您可以从默认样式重新应用它们。如果您正在使用Button控件,则尝试将事件附加到“Click”事件。
请注意,Button控件在内部考虑并处理PointerPressed、MouseLeftButtonDown、MouseLeftButtonUp事件,并引发Click事件。通常,Button控件不允许PointerPressed、MouseLeftButtonDown、MouseLeftButtonUp事件冒泡并触发。