简体   繁体   中英

[WPF]How to close popup

I'd like to close a popup automatically with controling StaysOpen value which is popup property. I've been opening it whenever text is entered or left mouse button is clicked.
StaysOpen is set to false .

    <Grid>
        <TextBox x:Name="textBox" PreviewMouseLeftButtonUp="textBox_PreviewMouseLeftButtonUp"/>
        <Popup IsOpen="{Binding IsOpen, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" OpacityMask="Transparent" StaysOpen="{Binding StaysOpen, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
               AllowsTransparency="True" PlacementTarget="{Binding ElementName=textBox}">
            <Border CornerRadius="5" Background="#FF303030" Width="{Binding ActualWidth, ElementName=textBox}">
                ...
            </Border>
        </Popup>
    </Grid>
private void textBox_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
   if ((sender as TextBox).Text.Length > 0)
   {
      IsOpen = !IsOpen;
   }
}

When text is entered in Textbox with Popup's IsOpen is true, can be closed automatically popup when clicked out side of the control. But, in a state of textBox_PreviewMouseLeftButtonUp function call with same situations, wouldn't be closed it automatically.(also IsOpen is true)

If i change to e.handel = true in textBox_PreviewMouseLeftButtonUp, then can be closed automatically, through clicking the outside of it. But it have serious problem on that, can not choose any of controls in the popup. so can not use this way.

How can I safely close the popup automatically by clicking out side of control?

You can use the TextBox 's LostKeyboardFocus event, which fires when the TextBox is no longer the destination for keyboard input (ie when the user clicks or tabs away from the control).

private void textBox_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
    IsOpen = false;
}

Also, for opening the popup, I might recommend using GotKeyboardFocus . PreviewMouseLeftButtonUp will only work if the user sets focus by left-clicking, but the user could also use tab, etc.

Not perfect, but I solved it.
I added MouseLeftButtonUpEvent instead of PreviewMouseLeftButtonUp.

textBox.AddHandler(MouseLeftButtonUpEvent,
                               new RoutedEventHandler(textBox_MouseLeftButtonUp),
                               true);

When external control is clicked, Pop up is closed automatically, and when TextBox is clicked, Pop up is opened.
However, If Pop up is displayed, When TextBox is clicked, Pop up isn't hidden.

Anyway, I think this is enough.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM