我正在 Template10
中使用示例代码 Busy.xaml
显示 ModalDialog
:
public static void SetBusy(bool busy, string text = null)
{
WindowWrapper.Current().Dispatcher.Dispatch(() =>
{
var modal = Window.Current.Content as ModalDialog;
var view = modal.ModalContent as Busy;
if (view == null)
modal.ModalContent = view = new Busy();
modal.IsModal = view.IsBusy = busy;
view.BusyText = text;
modal.CanBackButtonDismiss = true;
});
}
我可以使用 ALT+向左箭头
关闭此对话框,但在大多数桌面应用程序上,按 ESC
键通常也会关闭弹出窗口或对话框。
我尝试添加代码来处理 Busy.xaml
上的 KeyDown
,但当我按 ESC
或任何键时,此方法从未执行。
private void UserControl_KeyDown(object sender, KeyRoutedEventArgs e)
{
if (e.Key == VirtualKey.Escape)
{
e.Handled = true;
SetBusy(false);
}
}
那么,如何让这个ModalDialog
在用户按下ESC
键时关闭?
最佳答案
您必须将事件处理程序附加到 CoreWindow
的 CharacterReceived
事件。
修改SetBusy
方法:
public static void SetBusy(bool busy, string text = null)
{
WindowWrapper.Current().Dispatcher.Dispatch(() =>
{
var modal = Window.Current.Content as ModalDialog;
var view = modal.ModalContent as Busy;
if (view == null)
modal.ModalContent = view = new Busy();
modal.IsModal = view.IsBusy = busy;
view.BusyText = text;
modal.CanBackButtonDismiss = true;
// Attach to key inputs event
var coreWindow = Window.Current.CoreWindow;
coreWindow.CharacterReceived += CoreWindow_CharacterReceived;
});
}
CoreWindow_CharacterReceived
看起来像这样:
private static void CoreWindow_CharacterReceived(CoreWindow sender,
CharacterReceivedEventArgs args)
{
// KeyCode 27 = Escape key
if (args.KeyCode != 27) return;
// Detatch from key inputs event
var coreWindow = Window.Current.CoreWindow;
coreWindow.CharacterReceived -= CoreWindow_CharacterReceived;
// TODO: Go back, close window, confirm, etc.
}
关于c# - (UWP) 使用 ESC 键关闭 ModalDialog,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37685277/