views:

40

answers:

1

I want to have a command from my view model associated with F8, and don't know a great deal about input gestures. Must I wrap it in a routed command or is there another recommended way to do this?

Cheers,
Berryl

UPDATE

My original posting really had two pain points in them. The first was that prior to WPF 4 you couldn't bind a command directly to an input gesture or count on visual inheritance for the command's DataContext, and had to go through a CommandManager layer. That seems like the reason the MVVM Toolkit's CommandReference that NVM pointed out was useful, but now with WPF 4 this is fixed as the Command is an attached DP on the InputBinding, so all you need to do is something like:

<DataGrid.InputBindings>
    <KeyBinding Command="{Binding MyViewModel.MyCommand}" Key="F8" />
</DataGrid.InputBindings>

The second pain point to realize is that binding an input gesture to a command is not the same as associating the textual representation of that gesture to a menu item. So I need to do something like:

<MenuItem Header="{x:Static s:Strings.MyHeaderString}" Command="{Binding MyViewModel.MyCommand}" 
    InputGestureText="F8"/>

I spelled this out in the hopes that someone will either tell me I've got something wrong (or right). Assuming this is the best you can do then it's down to how much DRYness you can get and how to do that while keeping strictly visual elements out of your ViewModels. You could do this either by having some properties on your Command (ie, KeyGesture, KeyModifier) or having the "F8" in a resource file I suppose, depending on how much you need to reuse something and your point of view. Also on how many input gestures you have for the command!

+2  A: 

http://stackoverflow.com/questions/1468362/how-do-i-associate-a-keypress-with-a-delegatecommand-in-composite-wpf

This is your answer. Instead of Key="X" you should use Gesture="F8"

NVM
@NVM. Thanks for the reply. I'm not using MVVM toolkit but will take a look at how that does it. It also looks like WPF 4 obviates the need to do your own Freezable as described [here](http://blogs.msdn.com/b/llobo/archive/2009/10/29/new-wpf-features-key-gesture-binding.aspx?wa=wsignin1.0) but I need to digest this a bit more. I wasn't expecting to spend much time figuring out how to make the F8 key work on a command but maybe it's worth it. Cheers
Berryl
You dont really need the toolkit. CommandReference is a very simple class. You can just add the class to your project and be on your merry way. That said I'd prefer to use WPF built in stuff myself.
NVM
@NVM. I wound up making a class that adds both InputGestureText and a GestureKey (and some other properties) to my commands, so I can bind the former in a menuItem and the latter in a KeyBinding. I called the class CommandReference, so props to you. Cheers
Berryl