在WPF中动态添加KeyBindings [英] Dynamically add KeyBindings in WPF

查看:136
本文介绍了在WPF中动态添加KeyBindings的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以根据绑定的数据源动态定义KeyBindings?我有一个带有网格的屏幕,并且允许用户为其保存各种布局.我目前将网格上下文菜单绑定到布局名称(通过ViewModel),从而允许他们通过菜单切换布局.

Is it possible to dynamically define KeyBindings based on a bound data source? I have a screen with a grid and I allow users to save various layouts for it. I currently bind the grids context menu to the layout names (via the ViewModel), allowing them to switch layouts via the menu.

但是,我想将每个布局与快捷键相关联.由于快捷键是由用户定义的,因此我不能简单地在XAML窗口中添加许多<KeyBinding>元素.另一个问题是绑定需要提供布局名称作为命令参数.

However, I would like to associate each layout with a shortcut key. As the shortcut keys are defined by the user I can't simply add a number of <KeyBinding> elements in the window XAML. Another issue is the binding would need to supply the name of the layout as a command parameter.

有没有办法从动态来源动态创建一系列<KeyBinding>元素?

Is there any way to dynamically create a series of <KeyBinding> elements from a dynamic source?

作为测试,我已将绑定静态添加到我的视图XAML中,并且它们可以正常工作,但这只是为了测试我的概念:

As a test I have added the bindings statically to my view XAML and they work fine, but this was only to test my concept:

<UserControl.InputBindings>
    <KeyBinding Key="F7" Command="{Binding MyCommand}" CommandParameter="My Layout Name"/>
    <KeyBinding Key="F8" Command="{Binding MyCommand}" CommandParameter="My Other Layout Name"/>
</UserControl.InputBindings>

推荐答案

以下是我用来动态创建键绑定的代码,作为片段编辑器的一部分,该编辑器允许在热键上执行片段.

Here's code I use to create key bindings dynamically as part of a snippet editor that allows snippets to be executed on a hotkey.

除了前面的示例之外,它还演示了如何解析键组合的用户输入:

In addition to earlier examples it also demonstrates how to parse user input of key combos:

// example key combo from user input
var ksc = "Alt+Shift+M";
ksc = ksc.ToLower();

KeyBinding kb = new KeyBinding();

if (ksc.Contains("alt"))
    kb.Modifiers = ModifierKeys.Alt;
if (ksc.Contains("shift"))
    kb.Modifiers |= ModifierKeys.Shift;
if (ksc.Contains("ctrl") || ksc.Contains("ctl"))
    kb.Modifiers |= ModifierKeys.Control;

string key =
    ksc.Replace("+", "")
        .Replace("-", "")
        .Replace("_", "")
        .Replace(" ", "")
        .Replace("alt", "")
        .Replace("shift", "")
        .Replace("ctrl", "")
        .Replace("ctl", "");

key =   CultureInfo.CurrentCulture.TextInfo.ToTitleCase(key);
if (!string.IsNullOrEmpty(key))
{
    KeyConverter k = new KeyConverter();
    kb.Key = (Key)k.ConvertFromString(key);
}

// Whatever command you need to bind to
// CommandBase here is a custom class I use to create commands
// with Execute/CanExecute handlers
kb.Command = new CommandBase((s, e) => InsertSnippet(snippet),
                             (s,e) => Model.IsEditorActive);

Model.Window.InputBindings.Add(kb);

这篇关于在WPF中动态添加KeyBindings的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆