How should I go about adding KeyBinding
commands programmatically based on a string? In my xaml code I have properties like the following one.
<KeyBinding Key="Q" Command="{Binding AcceptAndNextCommand}" />
This works fine but I would like to be able to add this kind of key bindings dynamically and so I want to be able to add them programmatically. I have created a project settings file where each of my KeyBindings
is a separate row. This row possesses over a dictionary value where I have saved each keyboard key as a dictionary key and each command as a dictionary value; e.g.: {"Key":"Q", "Value":"AcceptAndNextCommand"}
. A String
to KeyBinding
Key conversion works fine but I'm not sure how to add a Command to the KeyBinding based on a String
. All the command strings in the dictionary value look like this "AcceptAndNextCommand". I was hoping that I could make this work with a CommandConverter cv
as in my example below but that does not seem to work.
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"]);
}
}
I based my implementation on the following question but it did not explain the addition of commands very well.