以编程方式添加KeyBindings命令

时间:2017-12-20 15:17:07

标签: c# wpf mvvm-light

如何根据字符串以编程方式添加KeyBinding命令?在我的xaml代码中,我有类似下面的属性。

<KeyBinding Key="Q" Command="{Binding AcceptAndNextCommand}" />

这很好但我希望能够动态添加这种键绑定,所以我希望能够以编程方式添加它们。我创建了一个项目设置文件,其中每个KeyBindings都是一个单独的行。这一行拥有一个字典值,我将每个键盘键保存为字典键,每个命令保存为字典值;例如:{"Key":"Q", "Value":"AcceptAndNextCommand"}StringKeyBinding密钥转换工作正常,但我不确定如何根据String向KeyBinding添加命令。字典值中的所有命令字符串都看起来像“AcceptAndNextCommand”。我希望我可以使用CommandConverter cv来完成这项工作,如下例所示,但这似乎不起作用。

private void KeyboardShortcuts()
    {
        foreach (SettingsProperty property in Properties.KeyboardBindings.Default.Properties)
        {
            var propertyValue = JsonConvert.DeserializeObject<Dictionary<string, string>>(
                Properties.KeyboardBindings.Default[property.Name].ToString());

            var keyBinding = new KeyBinding()
            {
                Key = (Key)new KeyConverter().ConvertFromString(propertyValue["Key"])
            };

            CommandConverter cv = TypeDescriptor.GetConverter(typeof(ICommand)) as CommandConverter;
            keyBinding.Command = (ICommand)cv?.ConvertFromString(propertyValue["Command"]);
        }
    }

我的实现基于以下question,但它没有很好地解释命令的添加。

1 个答案:

答案 0 :(得分:1)

您可以使用BindingOperations.SetBinding方法以编程方式创建绑定:

KeyBinding kb = new KeyBinding();
BindingOperations.SetBinding(kb, KeyBinding.CommandProperty, new Binding("AcceptAndNextCommand"));
...
InputBindings.Add(kb);

绑定的路径只是string

相关问题