C# · 12月 30, 2021

c# – 在TextBox焦点上打开WPF Popup

当焦点在文本框上时,我想打开一个弹出窗口
这是我写的代码: <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> <Text@R_374_2419@ 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 /> <Text@R_374_2419@ /> </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”,弹出窗口打开但从不关闭

我尝试将焦点放在弹出窗口之前打开它,但它不起作用

你有什么主意吗 ?

非常感谢,
尼达尔.

解决方法 将以下绑定添加到您的Popup声明中: StaysOpen=”{Binding ElementName=text,Path=IsKeyboardFocused}”

这应该是诀窍.