【问题标题】:Global Hotkey/Shortcut Manager in WPF Prism (MVVM)WPF Prism (MVVM) 中的全局热键/快捷方式管理器
【发布时间】:2013-09-26 00:07:49
【问题描述】:

如何在 wpf prism 应用程序中创建全局热键绑定,哪些模块可以动态添加热键?

我尝试了以下方法:

Window.InputCommands 绑定到我的 Hotkey 类的 ObservableCollection(使用
共同服务作为模型) --> InputCommands 不包含可访问的设置器

使用PreviewKeyDownEvent (EventToCommand) --> 没有可靠的方法来确定是否按下了 Ctrl 或 Alt(通过 我在 ViewModel 中)。我不喜欢这种方法。

有没有简单的方法来动态添加键绑定?

【问题讨论】:

    标签: c# wpf mvvm prism-4


    【解决方案1】:

    我不知道如何在纯 MVVM 中轻松动态地添加/删除。我想从代码隐藏中访问 InputBindings,因为您适当地注意到缺少设置器。但是,您可能倾向于仅通过查看以下两个来打破这种情况的设计:InputBindingsKeyGesture。所以考虑为你的 shell 创建一个自定义控件。

        public ObservableCollection<HotkeyModel> Hotkeys { get; private set; }
        public class HotkeyWindow : Window
        {
            HotKeys = new ObservableCollection<HotkeyModel>();
            HotKeys.CollectionChanged += new NotifyCollectionChangedEventHandler(HotkeysChanged);
        }
        void HotkeysChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if(e.Action == NotifyCollectionChangedAction.Add)
            {
                foreach(HotkeyModel hk in e.NewItems)
                    this.InputBindings.Add(new InputBinding(hk.Command), new KeyGesture(hk.Key, hk.Modifier));
            }
            else if(e. Action == NotifyCollectionChangedAction.Remove)
                ...
        }
    

    不要设置 InputBindings,而是添加和删除。保留 Hotkeys 的 ObservableCollection 并监听 CollectionChanged 事件。在添加和删除它们时,您可以在 InputBindings 中添加和删除。在创建 KeyGesture 时,您可以设置 Keyboard.Modifiers

    因此,您可以将此概念外推到具有附加/依赖属性和附加行为等的真实而彻底的 MVVM 设计中,以坚持我上面的示例暂时忽略的 View 和 ViewModel 分离。

    【讨论】:

    • 我添加了一个 AttatchedProperty,它接受一个 BindingCollection 并将更改反映到我的 Window.InputCommands 集合中。谢谢你的建议。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-28
    • 2016-05-25
    • 1970-01-01
    • 1970-01-01
    • 2019-10-02
    • 1970-01-01
    • 2015-04-28
    相关资源
    最近更新 更多