为什么WPF弹出窗口在单击其背景区域时会关闭?

Dre*_*kes 22 .net wpf focus popup

我有一个WPF Popup控件,其中包含一些编辑控件(列表框,文本框,复选框),其中包含相当多的空格.

Popup.StaysOpen设置为False,这是必需的.如果用户单击应用程序中的其他位置,则应视为编辑操作已中止,并且应关闭弹出窗口.

不幸的是,只要用户在弹出窗口的背景区域(编辑控件之间的空间)中单击,弹出窗口也会关闭.

我试过设置弹出窗口Focusable.我也试过设置弹出窗口的孩子(a Border)是可聚焦的.两个方面都没有运气.

此外,鼠标事件似乎通过弹出窗口.当我点击它时,弹出窗口下面的任何元素变得集中.尽管我PopupBorder(我正在点击)这两个IsHitTestVisibleFocusable设置为true.

Dre*_*kes 34

最后,我发现以下工作.鉴于...

<Popup x:Name="_popup"
       StaysOpen="False"
       PopupAnimation="Slide"
       AllowsTransparency="True">
Run Code Online (Sandbox Code Playgroud)

...我在调用后在构造函数中使用了这段代码InitializeComponent...

// Ensure that any mouse event that gets through to the
// popup is considered handled, otherwise the popup would close
_popup.MouseDown += (s, e) => e.Handled = true;
Run Code Online (Sandbox Code Playgroud)

  • 另一种让偶数处理程序陷入困境的方法是派生一个从“Popup”派生的“ArmouredPopup”类。它可以覆盖 `OnMouseDown`。我认为这是默认弹出类中的一个错误。 (2认同)

Rob*_*nee 7

在Popup和Border上忽略Focusable似乎很奇怪.当鼠标悬停在边框上时,我可以通过在触发器中更改StaysOpen来解决您的问题:

<Grid xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <ToggleButton x:Name="btnPop" Content="Pop!" Width="100" Height="50"/>
    <Popup Placement="Bottom" PlacementTarget="{Binding ElementName=btnPop}" IsOpen="{Binding IsChecked, ElementName=btnPop}">
        <Popup.Style>
            <Style TargetType="{x:Type Popup}">
                <Setter Property="StaysOpen" Value="False"/>
                <Style.Triggers>
                    <DataTrigger Binding="{Binding IsMouseOver, ElementName=brd}" Value="True">
                        <Setter Property="StaysOpen" Value="True"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Popup.Style>
        <Border x:Name="brd" Background="White" BorderThickness="1" BorderBrush="Black">
            <StackPanel>
                <TextBox Margin="10"/>
                <TextBlock Text="Some text is here." Margin="10"/>
                <TextBox Margin="10"/>
            </StackPanel>            
        </Border>
    </Popup>
</Grid>
Run Code Online (Sandbox Code Playgroud)