WPF button takes two clicks to fire Click event

2020-07-07 11:58发布

问题:

I have a TabItem which contains a calendar control and a button. The issue is that when the calendar's selected date is the same as the previously selected date, the button takes two clicks to fire its Click event.

I have implemented the selectedDatesChanged event of the calendar to solve this problem when the current selected date is different from the previous selection. The code is as below:

selectedDatesChanged(object sender, SelectionChangedEventArgs e)
{
    this.CaptureMouse();
    this.ReleaseMouseCapture();
}

What I'm looking for is a way to have the same effect shown in the above function when the selectedDate of the calendar does not differ from the previously selected date. I tried handling the GotFocus and MouseUp events, but it doesn't solve the problem.

Does anyone have any ideas on how I could solve this issue?

Thanks, Naveen

回答1:

This was the best answer I found on the web. It's still not perfect because it doesn't help with buttons that are marked as IsDefault or IsCancel

protected override void OnPreviewMouseUp(MouseButtonEventArgs e)
{
  base.OnPreviewMouseUp(e);
  if (Mouse.Captured is Calendar || Mouse.Captured is System.Windows.Controls.Primitives.CalendarItem)
  {
    Mouse.Capture(null);
  }
}


回答2:

You could simply write:

Mouse.Capture(null);

This will solve the issue of mouse holding focus