XAML:
<TextBox x:Name="textBox" GotFocus="textBox_GotFocus" LostFocus="textBox_LostFocus"/>
<Popup x:Name="pop" StaysOpen="True" Placement="Bottom" IsOpen="True" PlacementTarget="{Binding ElementName=textBox}" Width="{Binding Width, ElementName=textBox}" >
<TextBlock Background="White" Text="Some Message"/>
</Popup>
关于我目前拥有的代码:
private void textBox_GotFocus(object sender, RoutedEventArgs e)
{
pop.IsOpen = true;
}
private void textBox_LostFocus(object sender, RoutedEventArgs e)
{
pop.IsOpen = false;
}
我想在文本框获得焦点时显示弹出窗口,直到其他任何地方被点击或文本框失去焦点为止。所以StaysOpen = false不起作用。经过大量搜索后,我查找了组合框的代码here
我认为以下代码是设置StaysOpen = false导致弹出窗口在弹出窗口外单击时关闭的原因。我不知道如何覆盖此行为。 以下代码的确切链接为here(为简洁起见,删除了注释)
private static void OnLostMouseCapture(object sender, MouseEventArgs e)
{
Popup popup = sender as Popup;
if (!popup.StaysOpen)
{
PopupRoot root = popup._popupRoot.Value;
bool reestablishCapture = e.OriginalSource != root && Mouse.Captured == null && MS.Win32.SafeNativeMethods.GetCapture() == IntPtr.Zero;
if(reestablishCapture)
{
popup.EstablishPopupCapture();
e.Handled = true;
}
else
{
if(Mouse.Captured != root)
{
popup._cacheValid[(int)CacheBits.CaptureEngaged] = false;
}
bool newCaptureInsidePopup = Mouse.Captured != null && MenuBase.IsDescendant(root, Mouse.Captured as DependencyObject);
bool newCaptureOutsidePopup = !newCaptureInsidePopup && Mouse.Captured != root;
if(newCaptureOutsidePopup && !popup.IsDragDropActive)
{
popup.SetCurrentValueInternal(IsOpenProperty, BooleanBoxes.FalseBox);
}
}
}
}