为什么 MainWindow 没有从 Popup 获取焦点 child

Why MainWindow doesn't take the focus from a Popup child

我在从 MainWindow 打开的 Popup 中使用 Textbox 时遇到问题:如果 MainWindow 没有焦点打开Popup后,即使我之前点击它,我也无法在TextBox中写东西。似乎点击操作没有将焦点放在 MainWindow 上,因为它的不透明度仍然是 LightGray。 您可以在下面找到能够重现此问题的示例 VB.Net 代码:

MainWindow.xaml

<Window x:Class="MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" Height="400" Width="800" Title="FooWindow">

    <Grid>
        <Button Click="Button_Click" Content="Settings" Margin="10" />
    </Grid>
</Window>

MainWindow.xaml.vb

Imports System.Windows.Controls.Primitives

Class MainWindow
Sub New()

    ' This call is required by the designer.
    InitializeComponent()

    ' Add any initialization after the InitializeComponent() call.
End Sub

Private Sub Button_Click(sender As Object, e As RoutedEventArgs)
    Dim popup = New Popup()
    popup.HorizontalAlignment = HorizontalAlignment.Center
    popup.VerticalAlignment = VerticalAlignment.Center
    popup.PlacementTarget = Me
    popup.Width = 250
    popup.Height = 250
    popup.StaysOpen = True
    popup.Child = New TextBox() With {.Padding = New Thickness(20), .Height = 80, .Width = 100, .VerticalAlignment = VerticalAlignment.Center, .HorizontalAlignment = HorizontalAlignment.Center,
        .VerticalContentAlignment = VerticalAlignment.Center}
    popup.IsOpen = True
End Sub
End Class

如何重现此问题?

您可以通过为激活 window 的 PopupPreviewMouseLeftButtonDown 事件添加处理程序来解决此问题:

Private Sub Button_Click(sender As Object, e As RoutedEventArgs)
    Dim popup = New Popup()
    popup.HorizontalAlignment = HorizontalAlignment.Center
    popup.VerticalAlignment = VerticalAlignment.Center
    popup.PlacementTarget = Me
    popup.Width = 250
    popup.Height = 250
    popup.StaysOpen = True
    popup.Child = New TextBox() With {.Padding = New Thickness(20), .Height = 80, .Width = 100, .VerticalAlignment = VerticalAlignment.Center, .HorizontalAlignment = HorizontalAlignment.Center,
            .VerticalContentAlignment = VerticalAlignment.Center}
    AddHandler popup.PreviewMouseLeftButtonDown, AddressOf OnPopupMouseLeftButtonDown
    popup.IsOpen = True
End Sub

Private Sub OnPopupMouseLeftButtonDown(sender As Object, e As MouseButtonEventArgs)
    Activate()
End Sub