Triggering Silverlight Prism command with a keyboa

2019-02-19 02:14发布

问题:

Does anybody know whether one can trigger prism command with a shortcut? What I mean is I want to be able to define binding of a command to keyboard shortcut in declarative manner, like ClientUI does:

Are there any opensource libraries for that purpose? Or maybe code samples?

I found this question but I don't think that it answers mine.

回答1:

I've created such gesture trigger. And I'd like to share it with you guys. Basically, it is System.Windows.Interactivity trigger which can parse gestures represented as strings. Usage is as simple as in ClientUI:

<UserControl>
    <i:Interaction.Triggers>
        <behaviors:KeystrokeCommandTrigger Command="{Binding SaveChangesCommand}" Gesture="Ctrl+Shift+S" />
        <behaviors:KeystrokeCommandTrigger Command="{Binding RejectChangesCommand}" Gesture="Ctrl+Shift+R" />
        <behaviors:KeystrokeCommandTrigger Command="{Binding NewItemCommand}" Gesture="Ins" />
        <behaviors:KeystrokeCommandTrigger Command="{Binding DeleteSelectedItemCommand}" Gesture="Del" />
        <behaviors:KeystrokeCommandTrigger Command="{Binding UploadSomethingCommand}" Gesture="Ctrl+Shift+U" />
    </i:Interaction.Triggers>
</UserControl>

The code is on pastie.



回答2:

You could write an attached behavior that has a listens to the KeyUp event and then calls the Command. The complication comes in translating something like Gesture="Ctrl+Shift+A". You would need to write a parser to figure out exactly what key combination that string represents.