wpfvb.netxamllost-focus

Lose focus without interacting with component element in WPF


I have an element within a border, which I change it's visibility to visible, on the click of a button. When this button is clicked, and the border element is shown, I am putting the border element as the focused element:

        <Border Name="MasterBorder" BorderBrush="#737373" BorderThickness="2" CornerRadius="6" Margin="19,0,0,-25" HorizontalAlignment="Left" Width="26" Background="#595959" Grid.Column="0" Visibility="Hidden" LostFocus="c_LostFocus">
            <Slider Name="Master" Orientation="Vertical" Minimum="0" Maximum="100" Margin="2" />
        </Border>

And the click control is :

    Private Sub VolumeControl_Click(sender As Object, e As RoutedEventArgs)

            FocusManager.SetFocusedElement(MainPlayPage, MasterBorder)
    End Sub

If I do a GetFocusedElement, this returns the MasterBorder, so I presume this is correct. I have the

LostFocus="c_LostFocus"

on my button with the following being triggered.

Private Sub c_LostFocus(sender As Object, e As RoutedEventArgs)
    MessageBox.Show("Lost Focus")
End Sub

My issue is, when I open up the control, and it focuses, that all works fine, if I use the control slider, and then click outside the control, it fires the lost focus function. If I do not interact with the slider or border, and click somewhere outside of it to remove focus, my lost focus function does not trigger. Any ideas why this would be?

Additional handler in main window to change focus:

Public Sub OnPreviewMouseDownA(ByVal sender As Object, ByVal e As MouseButtonEventArgs)
    FocusManager.SetFocusedElement(MainWindow, MainWindow)

End Sub

Solution

  • The LostFocus event shoud be raised provided that you click on something that actually steals the focus from the Border.

    For example, clicking on a TextBlock won't cause the LostFocus event for the Border to get raised whereas clicking on a Button or another input control will.