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

时间:2010-08-12 16:11:10

标签: c# wpf wpf-controls

我想在焦点位于文本框时打开弹出窗口 这是我写的代码:

<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;
    }

如果我点击按钮一切正常 如果我单击文本框,弹出窗口将打开并关闭

如果我删除StaysOpen =“False”弹出窗口打开但从不关闭

我尝试在打开它之前将焦点设置在弹出窗口上,但它不能正常工作

你有什么想法吗?

非常感谢, 尼达尔。

1 个答案:

答案 0 :(得分:16)

将以下绑定添加到Popup声明:

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

这应该可以解决问题。

相关问题