Search code examples
c#wpflostfocus

LostFocus not firing


Got a bit stuck and could use some help. To achieve: whenever click outside of the StackPanel - it Visibilty should change to Hidden.

Pretty easy one, I wrote the next condition:

private void pnlLeftMenu_LostFocus(object sender, RoutedEventArgs e)
    {
        if (pnlLeftMenu.IsFocused == false)
        {
            pnlLeftMenu.Visibility = Visibility.Hidden;
        }
    }

Where pnlLeftMenu is the panel, which should be triggered. Here is the xaml piece, with described properties:

    <StackPanel x:Name="pnlLeftMenu"                    
                Orientation="Vertical" 
                Height="475" 
                HorizontalAlignment="Left" 
                VerticalAlignment="Bottom"
                Margin="57,0,0,0"
                Visibility="Hidden"
                Background="{StaticResource BlueFadedBrush}" 
                IsVisibleChanged="pnlLeftMenu_IsVisibleChanged" 
                Focusable="True"
                LostFocus="pnlLeftMenu_LostFocus" >

No worries about the fact, that it is already hidden - it is a side menu, which become vissible on button click. That part works fine.

So the question is: what am I missing? Cause when it looks like this - the click outside of the panel does't give any reaction.


Solution

  • can you add a click event to the parent container of stack panel and inside the click event handler try like

       if (pnlLeftMenu.IsVisible)
        {
            pnlLeftMenu.Visibility = Visibility.Hidden;
        }