Search code examples
c#wpfmvvmkey-bindings

Dynamically add KeyBindings to Buttons


As you can see on this question I need dynamic buttons. Now I need to add some KeyBindings to those buttons. The shortcuts are stored in my Product class as string. I tried using a ListBox/ListView like I used for creating my buttons, but I can't add KeyBindings there.

Example: Button is bound to object "Coke" where "C" is the shortcut. If I click on this button my OrderCommand command is executed and my bound object is used as its parameter. The same should work if I press "C".

Also I need it to work with dupes, let's say I have two products with the shortcut "C", and if I press "C" not the first button is pressed. Pressing "C" will switch between those two buttons and if I press enter, the Command will be executed.


Solution

  • You can restyle buttons inside the list control to set their InputBindings

    <ListBox ItemsSource={Binding Buttons}>
        <ListBox.Resources>
             <Style x:Key="{x:Type Button}" BasedOn="{x:Type Button}">
                  <Setter Property="Button.InputBindings"/>
                       <Setter.Value>
                            <KeyBinding Key="C" Command="{Binding OrderCommand}" />     
                       </Setter.Value>
                  </Setter>
             </Style>
        </ListBox.Resources>
    </ListBox>