首先在XAML中定义监听按键 Window.InputBindings KeyBinding Key="Esc" Command="{Binding CloseWindowCommand}" CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}" //Window.InputBindin
首先在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);