繁体   English   中英

[WPF]如何关闭弹窗

[英][WPF]How to close popup

我想通过控制作为弹出属性的 StaysOpen 值自动关闭弹出窗口。 每当输入文本或单击鼠标左键时,我都会打开它。
StaysOpen设置为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;
   }
}

当在Textbox中输入文本时Popup的IsOpen为true,在控件外边点击时可以自动关闭弹出窗口。 但是,在 textBox_PreviewMouseLeftButtonUp function 的 state 调用中,在相同情况下不会自动关闭它。(IsOpen 也是如此)

如果我在 textBox_PreviewMouseLeftButtonUp 中更改为 e.handel = true,则可以通过单击外部自动关闭。 但它有一个严重的问题,无法选择弹出窗口中的任何控件。 所以不能用这种方式。

如何通过单击控制之外的方式安全地自动关闭弹出窗口?

您可以使用TextBoxLostKeyboardFocus事件,该事件在TextBox不再是键盘输入的目标时触发(即,当用户单击或制表符离开控件时)。

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

另外,为了打开弹出窗口,我可能会推荐使用GotKeyboardFocus PreviewMouseLeftButtonUp仅在用户通过左键单击设置焦点时才有效,但用户也可以使用选项卡等。

不完美,但我解决了。
我添加了 MouseLeftButtonUpEvent 而不是 PreviewMouseLeftButtonUp。

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

点击外部控件时自动关闭Popup,点击TextBox时打开Popup。
但是,如果显示弹出窗口,单击文本框时,弹出窗口不会隐藏。

无论如何,我认为这已经足够了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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