背景領域をクリックするとWPFポップアップが閉じるのはなぜですか?
質問
WPF Popup
コントロールがあり、そこにはいくつかの編集コントロール(リストボックス、テキストボックス、チェックボックス)がかなりの空白でレイアウトされています。
Popup.StaysOpen
は False
に設定されていますが、これは必須です。ユーザーがアプリケーションの他の場所をクリックすると、編集操作は中止されたと見なされ、ポップアップが閉じます。
残念ながら、ユーザーがポップアップの背景領域(編集コントロール間のスペース)をクリックすると、ポップアップも閉じます。
ポップアップを Focusable
に設定しようとしました。また、ポップアップの子( Border
)をフォーカス可能に設定しようとしました。どちらの面でも運がありません。
さらに、マウスイベントはポップアップを通過するようです。クリックするとポップアップの下にある要素がフォーカスされます。これは、 IsHitTestVisible
と Focusable
の両方を持つ Popup
と Border
(クリック先)の両方にもかかわらずです。 true
に設定します。
解決
最終的に、次のことがうまくいくことがわかりました。与えられた...
<Popup x:Name="_popup"
StaysOpen="False"
PopupAnimation="Slide"
AllowsTransparency="True">
... 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;
他のヒント
Focusable on the Popup and Borderを無視するのは奇妙に思えます。マウスが境界線上にあるときにトリガーで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>
私の推測では、いくつかの透明性の問題が進行中です。ポップアップで背景ブラシを設定してみてください。
ToggleButtonまたは他の種類のボタンにPopupをネストしませんか?その後、ポップアップレベルでルーティングイベントを停止すると、動作するようになります。
StayOpen = trueを設定し、ポップアップのMouseLeaveイベントtimer.Start()でタイマーを設定できます(3秒後など)。MouseEnterイベントでこのポップアップを閉じます。やめる()。 動作します。