【问题标题】:Programmatically add KeyBindings Commands以编程方式添加 KeyBindings 命令
【发布时间】:2017-12-20 15:17:06
【问题描述】:

我应该如何基于字符串以编程方式添加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,但它并没有很好地解释添加命令。

【问题讨论】:

    标签: c# wpf mvvm-light


    【解决方案1】:

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

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

    绑定的路径只是一个string

    【讨论】:

    • 这不会在视图中设置键绑定吗?我只是运行它,它没有抛出任何错误,但也没有发生任何事情。
    • 在视图中?它设置您传递给 SetBinding 方法的 KeyBinding 命令...当然,您需要以某种方式将您以编程方式创建的 KeyBinding 添加到视图中。或者您还打算在哪里使用 KeyBinding?
    • 这就是我的评论的意思。然后如何将它添加到应该使用键绑定的视图中?
    • 它在用作主视图的 UserControl 后面的代码中。
    • 只需将您以编程方式创建的 KeyBinding 添加到 InputBindings 集合即可:this.InputBindings.Add(kb);
    猜你喜欢
    • 2016-06-06
    • 2011-02-02
    • 2011-04-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-29
    • 2021-08-23
    • 2018-04-10
    • 1970-01-01
    相关资源
    最近更新 更多