WPF MVVM模式下如何通过ESC键安全退出窗口?

2026-05-01 01:3312阅读0评论SEO问题
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计180个文字,预计阅读时间需要1分钟。

WPF MVVM模式下如何通过ESC键安全退出窗口?

首先在XAML中定义监听按键+Window.InputBindings+KeyBinding+Key=Esc+Command={Binding CloseWindowCommand} CommandParameter={Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}} // Window.InputBinding

首先在XAML中定义监听按键

<Window.InputBindings> <KeyBinding Key="Esc" Command="{Binding CloseWindowCommand}" CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}" /> </Window.InputBindings>

此处,绑定了一个ICommand命令CloseWindowCommand。

在后台ViewModel中定义一个ICommand命令

/// <summary> /// 窗口关闭 /// </summary> public DelegateCommand<Window> CloseWindowCommand { get; set; }

定义一个关闭窗口的方法。

阅读全文

本文共计180个文字,预计阅读时间需要1分钟。

WPF MVVM模式下如何通过ESC键安全退出窗口?

首先在XAML中定义监听按键+Window.InputBindings+KeyBinding+Key=Esc+Command={Binding CloseWindowCommand} CommandParameter={Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}} // Window.InputBinding

首先在XAML中定义监听按键

<Window.InputBindings> <KeyBinding Key="Esc" Command="{Binding CloseWindowCommand}" CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}" /> </Window.InputBindings>

此处,绑定了一个ICommand命令CloseWindowCommand。

在后台ViewModel中定义一个ICommand命令

/// <summary> /// 窗口关闭 /// </summary> public DelegateCommand<Window> CloseWindowCommand { get; set; }

定义一个关闭窗口的方法。

阅读全文