简体   繁体   English

在TextBox焦点上打开WPF弹出窗口

[英]Open WPF Popup on TextBox focus

I want to open a popup when the focus is on a text box Here is the code I wrote : 当焦点在文本框上时,我想打开一个弹出窗口这是我写的代码:

<Window x:Class="Testpopup.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <StackPanel>
        <TextBox  x:Name="text" GotKeyboardFocus="text_GotKeyboardFocus" />
        <Button Click="Button_Click"  Content="but"/>
        <Popup x:Name="popup" Width="100" Height="100" PlacementTarget="{Binding ElementName=text}"
            StaysOpen="False">
            <Grid>
                <StackPanel>
                    <DatePicker />
                    <TextBox />
                </StackPanel>
            </Grid>
        </Popup>

    </StackPanel>
</Grid>

 private void Button_Click(object sender, RoutedEventArgs e)
    {
        popup.IsOpen = true;
    }

    private void text_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
    {
        popup.IsOpen = true;
    }

If I Click on the button everything works fine If I Click on the text box the popup open and close 如果我单击按钮一切正常如果我单击文本框弹出打开和关闭

If I remove StaysOpen="False" the popup open but never close 如果我删除StaysOpen =“False”弹出窗口打开但从不关闭

I try to set the focus on the popup before opening it but it does not work as well 我尝试在打开它之前将重点放在弹出窗口上,但它也不起作用

Do you have any idea ? 你有什么主意吗 ?

Many thanks, Nidal. 非常感谢,Nidal。

Add the following binding to your Popup-declaration: 将以下绑定添加到Popup声明:

StaysOpen="{Binding ElementName=text,Path=IsKeyboardFocused}"

This should do the trick. 这应该可以解决问题。

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

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