c# - (UWP) 使用 ESC 键关闭 ModalDialog

标签 c# xaml uwp template10

我正在 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键时关闭?

最佳答案

您必须将事件处理程序附加到 CoreWindowCharacterReceived 事件。

修改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/

相关文章:

c# - UWP 中的 DataTable 类在哪里?

c++ - 当有许多函数要导入时替代 `LoadPackagedLibrary`

c# - .NET Compact Framework 中标签/文本框的自动调整大小

c# - 从另一个 View 的中心开始到其左边界的水平展开动画

c# - ControlTemplate Storyboard 颜色动画问题

c# - 如何在 UWP Windows 10 应用程序中将 InkCanvas 渲染为图像?

c# - asp :TextBox? 上的动态 ID

c# - NpgSql 调用函数/例程

c# - 更新包后,未将对象引用设置为 _Layout.cshtml 中的对象实例

c# - 自动生成 xaml ResourceDictionary