I have very simple scenario here. Look at layout, please:
<Grid>
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<TextBox Grid.Row="0"></TextBox>
<DatePicker Grid.Row="1"
Name="_datePicker"
LostFocus="_datePicker_OnLostFocus"></DatePicker>
</Grid>
and codebehind:
private void _datePicker_OnLostFocus(object sender, RoutedEventArgs e)
{
Debug.WriteLine("LostFocuse");
}
So, trouble is when I pick up some date and click TextBox
then, event LostFocus
fires 7 (seven!) times. One when DatePicker
really lost focus when I ckicked on TextBox
and remaining six times totally are not explainable for me.
How can I fix it? I need only one fireing of this event. Or may be I can use some other event? I tried LostKeyBoardFocus
with the same result.
LostFocus is a routed event with route strategy set to Bubble
. By bubble it means it will bubble up to its parent till root window until handled somewhere by explicitly setting e.Handled = true;
.
So, that means even when child control lose focus it will bubble up to your datePicker that's why you see multiple hits to your method.
You can check for property IsKeyboardFocusWithin
which returns if focus is within your control. Since you are not interested in listening to child lost focus event, you can check for this property in your handler like this and execute your code only when actual focus is lost by datePicker:
private void _datePicker_OnLostFocus(object sender, RoutedEventArgs e)
{
DatePicker picker = sender as DatePicker;
if (!picker.IsKeyboardFocusWithin)
{
System.Diagnostics.Debug.WriteLine("LostFocuse");
}
}