1. 程式人生 > WINDOWS開發 >【WPF/WAF】設定快捷鍵(Shortcut Key)

【WPF/WAF】設定快捷鍵(Shortcut Key)

原文:【WPF/WAF】設定快捷鍵(Shortcut Key)

基於WAF框架:WPF Application Framework (WAF)

View層XAML中設定熱鍵。

    <Window.InputBindings>
        <!--<KeyBinding Command="{Binding SaveCommand}" Key="S" Modifiers="Control"/>-->
        <KeyBinding Command="{Binding AboutCommand}" Key="F1"/>
    </
Window.InputBindings>

ViewModel中定義該AboutCommand命令。


        private ICommand aboutCommand;
        public ICommand AboutCommand
        {
            get { return aboutCommand; }
            set { SetProperty(ref aboutCommand,value); }
        }

控制層寫AboutCommand命令的實現。

namespace WafApplication1.Applications.Controllers
{ [Export] internal class ApplicationController { private readonly ShellViewModel shellViewModel; private readonly DelegateCommand aboutCommand; [ImportingConstructor] public ApplicationController(ShellViewModel shellViewModel) { this
.shellViewModel = shellViewModel; this.aboutCommand = new DelegateCommand(AboutCommand); } private void AboutCommand() { MessageBox.Show("F1 Command!"); } public void Initialize() { shellViewModel.AboutCommand = this.aboutCommand; } public void Run() { shellViewModel.Show(); } public void Shutdown() { } } }

執行該專案,按F1即可看到彈出彈窗。

技術分享圖片


新的問題

給該Window窗體註冊的快捷鍵,必須要在該窗體獲得焦點時快捷鍵才有效。如果該窗體內有別的控制元件(如ListBox)獲取了焦點,再點選該快捷鍵將不起效果。這時候,可考慮同樣給該ListBox控制元件新增相同的快捷鍵命令。

<!-- 快捷鍵 -->
<ListBox.InputBindings>
    <KeyBinding Command="{Binding ShortcutScaleCommand}" Key="F1"/>
</ListBox.InputBindings>