您可以使用计时器以及 PointerPressed 和 PointerReleased 事件来模拟此过程。
你可以像这样创建简单的计时器
private bool _isTimerActive = false;
private int _timeInMS = 0;
private const int Delay = 1500; // wait for 1.5 sec
private async void StartTimer()
{
_isTimerActive = true;
while (_isTimerActive)
{
await Task.Delay(10);
_timeInMS += 10;
if (_timeInMS > Delay)
{
_holdingAction(null, null); // Do the suitable action after holding for 1.5 secounds
StopTimer();
}
}
}
private void StopTimer()
{
_isTimerActive = false;
_timeInMS = 0;
}
那么您必须为 .cs 中的每个按钮添加事件处理程序,因为按钮控件不会允许 PointerPressed 和 PointerReleased 事件触发。
像那样:
MyButton.AddHandler(PointerPressedEvent, new PointerEventHandler(Button_PointerPressed), true);
MyButton.AddHandler(PointerReleasedEvent, new PointerEventHandler(Button_PointerReleased), true);
最后,您可以使用委托来定义每个按钮的操作
private delegate void HoldingAction(object sender, HoldingRoutedEventArgs e);
private HoldingAction _holdingAction;
// your Long-press event
private void Button_Holding(object sender, HoldingRoutedEventArgs e)
{
//Your awesome code here.
}
private void Button_PointerPressed(object sender, PointerRoutedEventArgs e)
{
StartTimer();
_holdingAction = Button_Holding;
}
private void Button_PointerReleased(object sender, PointerRoutedEventArgs e)
{
StopTimer();
}