我正在使用WPF Popup。弹出窗口包含一些键盘。 我想在用户点击文本框时打开弹出窗口,并且在文本框具有焦点时不隐藏弹出窗口。 此外,当用户点击远离弹出窗口的某个地方时,我需要隐藏弹出窗口。 这是xaml代码:
<Grid>
<StackPanel>
<TextBox x:Name="textBox" GotKeyboardFocus="textBox_GotFocus" MouseDown="textBox_MouseDown" />
<Popup x:Name="popup" Width="100" Height="100" PlacementTarget="{Binding ElementName=textBox}" Placement="Bottom"
StaysOpen="{Binding ElementName=text,Path=IsKeyboardFocused}">
<Grid Background="Blue">
</Grid>
</Popup>
</StackPanel>
</Grid>
这是c#代码:
private void textBox_GotFocus(object sender, KeyboardFocusChangedEventArgs e)
{
popup.IsOpen = true;
}
private void textBox_MouseDown(object sender, MouseButtonEventArgs e)
{
popup.IsOpen = true;
}
我发现绑定可以帮助:
StaysOpen="{Binding ElementName=,Path=IsKeyboardFocused}"
但TextBox永远不会隐藏。如果我设置StaysOpen =&#34; False&#34; TextBox永远不会显示
答案 0 :(得分:0)
您可以处理LostKeyboardFocus
事件并检查新的焦点元素是TextBox
本身还是Popup
的子元素:
private void textBox_GotFocus(object sender, KeyboardFocusChangedEventArgs e)
{
popup.IsOpen = true;
}
private void textBox_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
var newFocusedElement = e.NewFocus as DependencyObject;
//if the focused element is a child of the window, it can't be the child of the popup
if (newFocusedElement == null || FindParent<Window>(newFocusedElement) != null)
popup.IsOpen = false;
}
private void popup_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
popup.IsOpen = e.NewFocus == textBox;
}
private static T FindParent<T>(DependencyObject dependencyObject) where T : DependencyObject
{
var parent = VisualTreeHelper.GetParent(dependencyObject);
if (parent == null) return null;
var parentT = parent as T;
return parentT ?? FindParent<T>(parent);
}
示例XAML:
<StackPanel>
<TextBox x:Name="textBox" GotKeyboardFocus="textBox_GotFocus" LostKeyboardFocus="textBox_LostKeyboardFocus" />
<Popup x:Name="popup" Width="100" Height="100" PlacementTarget="{Binding ElementName=textBox}"
LostKeyboardFocus="popup_LostKeyboardFocus"
Placement="Bottom">
<Grid x:Name="popupRoot" Background="Blue">
<TextBox Margin="10" />
</Grid>
</Popup>
<TextBox />
</StackPanel>