您可以这样做的一种方法是绑定到 MouseDown 和 MouseUp 事件。使用在 MouseDown 上启动的秒表之类的东西,并检查在 MouseUp 上经过的时间量。如果少于 3 秒,请执行 Click() 操作。如果超过 3 秒,请执行 LongClick() 操作。
private void Button_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
stopwatch = new Stopwatch();
stopwatch.Start();
}
private void Button_PreviewMouseUp(object sender, MouseButtonEventArgs e)
{
stopwatch.Stop();
if (stopwatch.ElapsedMilliseconds >= 3000)
{
// do Click()
}
else
{
// do LongClick
}
}
这是RepeatButton的解决方案:
private bool isLongClick;
private bool hasAlreadyLongClicked;
private void RepeatButton_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
isLongClick = false;
hasAlreadyLongClicked = false;
stopwatch = new Stopwatch();
stopwatch.Start();
}
private void RepeatButton_Click(object sender, RoutedEventArgs e)
{
if (!hasAlreadyLongClicked && stopwatch.ElapsedMilliseconds >= 3000)
{
hasAlreadyLongClicked = true;
isLongClick = true;
// do your LongClick action
}
}
private void RepeatButton_PreviewMouseUp(object sender, MouseButtonEventArgs e)
{
if (!isLongClick)
{
// do short click action
}
}
这里的诀窍是,RepeatButton 基本上只是一个在每个间隔触发 Click 的 Button。因此,如果我们在 PreviewMouseDown 上为按钮启动秒表,我们可以在每次 Click 事件触发时检查秒表上的经过时间,并根据结果修改我们的操作。