Search code examples
wpfcommandtogglebuttoninputbinding

How to handle InputBinding Commands and ToggleButtons?


I have an InputBinding with the intention that F6 works as a shortcut to activate an edit mode, like this:

<Window.InputBindings>
    <KeyBinding Gesture="F6" Command="{Binding Path=ActivateEdit}"/>
</Window.InputBindings>

The button itself looks like this:

<ToggleButton Height="26" Width="26" Margin="0,0,1,1" Padding="1" 
                            ToolTip ="Bearbeiten (F6)" 
                            Command="{Binding ActivateEdit}"               
                            IsChecked="{Binding IsEditPressed, Converter={StaticResource boolToNullableBoolConverter}}"
                            IsTabStop="False" BorderThickness="0" BorderBrush="{x:Null}" Focusable="False">
    <Image Source="/Images/Edit.ico" Stretch="Fill" Height="16" Width="16"/>
</ToggleButton>

If the button is pressed manually the command is triggered. Also if the user presses F6. But in that case the button doesn't get the IsChecked state. How can I accomplish this without coding a different command for the KeyBinding?


Solution

  • Make your command "toggle" the IsEditPressed property, ideally this would be the only thing that needs to be done which makes it easier to keep everything in sync. You then would not even need the command on the ToggleButton itself as the IsChecked binding is enough.