首先在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; }
定义一个关闭窗口的方法。
/// <summary>
/// 关闭窗口
/// </summary>
/// <param name="obj"></param>
private void CloseWindow(Window obj)
{
var window = (Window)obj;
if (window != null)
{
window.Close();
}
}
初始化的时候,进行命令绑定。
CloseWindowCommand = new DelegateCommand<Window>(CloseWindow);
标签:窗口,MVVM,CloseWindowCommand,按下,window,WPF,Window
From: https://www.cnblogs.com/utopio/p/17638591.html