【发布时间】:2017-12-20 15:17:06
【问题描述】:
我应该如何基于字符串以编程方式添加KeyBinding 命令?在我的 xaml 代码中,我有如下属性。
<KeyBinding Key="Q" Command="{Binding AcceptAndNextCommand}" />
这很好用,但我希望能够动态添加这种键绑定,因此我希望能够以编程方式添加它们。我创建了一个项目设置文件,其中我的每个 KeyBindings 都是单独的行。这一行拥有一个字典值,其中我将每个键盘键保存为字典键,将每个命令保存为字典值;例如:{"Key":"Q", "Value":"AcceptAndNextCommand"}。 String 到 KeyBinding 的密钥转换工作正常,但我不确定如何基于 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