当我在弹出窗口外单击或单击Esc按钮WPF时关闭弹出窗口
问题描述:
当我们点击弹出窗口或点击Esc按钮时,如何关闭弹出窗口。
How to close the popup when we click outside the popup or clicking the Esc button.
_tablePopup = new Popup();
_tablePopup.Child = sp;
_tablePopup.Placement = System.Windows.Controls.Primitives.PlacementMode.Right;
_tablePopup.PlacementTarget = _tableButton;
_tablePopup.StaysOpen = true;
_tablePopup.IsOpen = true;
答
您好GeethuSree,
Hi GeethuSree,
>>当我们点击弹出窗口或点击Esc按钮时,如何关闭弹出窗口。
>>How to close the popup when we click outside the popup or clicking the Esc button.
请尝试以下示例,该示例使用切换按钮和键盘事件:
Please try the following sample, which use Toggle button and keyboard event:
#Xaml
<Window x:Class="WpfApp1.PopupWindow.Window1"
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"
xmlns:local="clr-namespace:WpfApp1.PopupWindow"
mc:Ignorable="d"
Title="Window1" Height="300" Width="300">
<Grid>
<ToggleButton x:Name="buttonShowPopup" Width="100" Height="25" Content="Show Popup"/>
<Popup x:Name="Popup1"
PlacementTarget="{Binding ElementName = buttonShowPopup}"
VerticalOffset="0"
HorizontalOffset="5"
Placement="Right"
PopupAnimation="Fade"
AllowsTransparency="True"
IsOpen="{Binding ElementName=buttonShowPopup, Path=IsChecked, Mode=TwoWay}"
StaysOpen="False">
<Border Background="Beige" BorderBrush="Black" BorderThickness="2" Padding="10">
</Border>
</Popup>
</Grid>
</Window>
#Code背后
#Code Behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace WpfApp1.PopupWindow
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
this.PreviewKeyDown += new KeyEventHandler(HandleEsc);
}
private void HandleEsc(object sender, KeyEventArgs e)
{
if (e.Key == Key.Escape)
Popup1.IsOpen = false;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Popup1.IsOpen = true;
}
}
}
祝你好运,
张龙