在WPF中动态添加KeyBindings

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

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

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

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

     

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

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

 // 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); 

有几种方法可以做到这一点,最简单的方法是创建一个转换器,它将返回一个键,具体取决于命令名称(基本上它是一个查找,你的布局名称是一个键,键是一个值)。 如果你需要处理更复杂的客户,它会变得稍微复杂一点,我会为它制作样品:

这是XAML: