I am using Prism and have a CompositeCommand
in an ApplicationCommands.cs
class:
public CompositeCommand ShowSourceFormattingCommand { get; } = new CompositeCommand(true);
I have a DelegateCommand<bool?>
registered to this CompositeCommand
:
public DelegateCommand<bool?> ShowSourceFormattingCommand { get; }
...
Services.ApplicationCommands.ShowSourceFormattingCommand.
RegisterCommand(ShowSourceFormattingCommand);
It is then associated with a command handler:
ShowSourceFormattingCommand =
new DelegateCommand<bool?>(changeDisplayCommandsHandler.OnShowSourceFormattingSelect).
ObservesCanExecute(() => IsActive);
...
public void OnShowSourceFormattingSelect(bool? selected)
{
Services.EventService.GetEvent<ShowSourceFormattingEvent>().Publish(selected ?? false);
}
It is data bound to a ToggleButton
in the UI and works well. However, when I try to associate a keyboard shortcut with it, it does not work (using the specified keys).
<KeyBinding Modifiers="Ctrl+Shift" Key="S"
Command="{Binding ShowSourceFormattingCommand}" />
This is because there is no value for the bool parameter, so it is null. If the option is toggled on in the UI, then the keyboard shortcut will toggle it to off, but never back on. Note that the ComandParameter
of the KeyBinding
class is not passed through to the associated command, but it wouldn't help if it was, because I need it to to alternate between true and false.
<KeyBinding Modifiers="Ctrl+Shift" Key="S" Command="{Binding ShowSourceFormattingCommand}"
CommandParameter="True" />
Therefore, I tried implementing the CommandReference
object, as specified in the How do I associate a keypress with a DelegateCommand in Composite WPF?, but it gives the same result, with the nullable bool parameter always being null.
I then tried implementing another command for the KeyBinding
, which would toggle the value:
public CompositeCommand ShowSourceFormattingKeyboardCommand { get; } =
new CompositeCommand(true);
...
public DelegateCommand ShowSourceFormattingKeyboardCommand { get; }
...
Services.ApplicationCommands.ShowSourceFormattingKeyboardCommand.
RegisterCommand(ShowSourceFormattingKeyboardCommand);
...
ShowSourceFormattingKeyboardCommand =
new DelegateCommand(changeDisplayCommandsHandler.OnToggleShowSourceFormattingCommand).
ObservesCanExecute(() => IsActive);
...
private bool _isSourceFormattingShown = false;
public void OnToggleShowSourceFormattingCommand()
{
_isSourceFormattingShown = !_isSourceFormattingShown;
OnShowSourceFormattingSelect(_isSourceFormattingShown);
}
This works and correctly toggles the function on and off, but there is no indication in the state of the button when the keyboard shortcut is used. This is the same with all of these methods. My question is how are these nullable bool commands supposed to be wired up to a ToggleButton
to correctly update the visual state of the button, eg. toggle the button on and off?