How to Close a Window in WPF on a escape key

前端 未结 4 2104
青春惊慌失措
青春惊慌失措 2020-12-24 10:49

Possible Duplicate:
How can I assign the 'Close on Escape-key press' behavior to all WPF windows within a project?

4条回答
  •  渐次进展
    2020-12-24 11:22

    One line to put after InitializeComponent():

     PreviewKeyDown += (s,e) => { if (e.Key == Key.Escape) Close() ;};
    

    Please note that this kind of code behind does not break MVVM pattern since this is UI related and you don't access any viewmodel data. The alternative is to use attached properties which will require more code.

提交回复
热议问题