The question is pretty simple: How do I prevent LostFocus from getting raised on MouseDown on a control that already got focus?
I have the following control (temporary test with all the event bindings):
<Grid Name="gBase" Focusable="True" MouseUp="SetFocus" MouseDown="SetFocus" MouseMove="gBase_MouseMove" PreviewDragEnter="gBase_PreviewDragEnter" LostFocus="gBase_LostFocus" GotFocus="gBase_GotFocus" Background="DarkRed" Width="500" Height="250" />
And the following code behind:
private void SetFocus(object sender, MouseButtonEventArgs e)
{
Grid g = sender as Grid;
g.Focus();
}
private void gBase_LostFocus(object sender, RoutedEventArgs e)
{
Grid g = sender as Grid;
g.Background = Brushes.DarkRed;
}
private void gBase_GotFocus(object sender, RoutedEventArgs e)
{
Grid g = sender as Grid;
g.Background = Brushes.Aquamarine;
}
private void gBase_MouseMove(object sender, MouseEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
Grid g = sender as Grid;
g.Focus();
}
}
private void gBase_PreviewDragEnter(object sender, DragEventArgs e)
{
Grid g = sender as Grid;
g.Focus();
}
The behaviour is almost of that I want to achieve, if I click on the Grid it get focus.
The problem is that if the Grid already got focus it will lose it while I have the mouse button down and not regain it until I release or move. My prefered behaviour would be to prevent that it loses focus in the first place.
The problem was that the parent ScrollViewer stole focus.
This was solved by using the event
MouseLeftButtonDownand setting theMouseButtonEventArgs.Handledtotrueto prevent further handling of the event.Working code: