2

This question gives a clean method for binding a key at the window level to a ViewModel command in XAML. This is pretty fantastic, but it doesn't allow for customization of the key being used. Is it possible to bind the "key" value to the viewmodel, and if so, what type of value is a "key" in csharp?

<Window.InputBindings>
<KeyBinding Key="{Binding RefreshKey}"
            Command="{Binding RefreshCommand}" />

Or is it possible to add window-level keybindings in the code? The same question has a solution for putting it in the code-behind, but I would prefer to keep the code in the ViewModel if its possible.

Community
  • 1
  • 1
Kyeotic
  • 19,697
  • 10
  • 71
  • 128

2 Answers2

1

http://msdn.microsoft.com/en-us/library/system.windows.input.keygesture.aspx

For KeyGesture XAML usages, the property that is generally set in XAML is Gesture, in cases where the gesture represents both a standard key and a modifier key

... Note that the XAML usage does not directly declare a element. That object element usage is not possible because KeyGesture does not expose a public default constructor. Instead, the XAML usage uses the typeconverter behavior to declare an entire KeyGesture inline as the Gesture attribute value.

I think you can return a KeyGesture object to bind a Key property or you can always return a composed string and it will be automatically converted

MaRuf
  • 1,834
  • 2
  • 19
  • 22
0

The property type is the enumeration Key, so it should be simple enough to expose this from your view model and bind to it. However, as noted in the question you linked to, support for bindings in KeyBinding were not added until WPF 4.

EDIT: didn't realize you were asking for a way to invoke a command as a result of multiple key strokes. Please see my blog post here discussing how I solved this. You may need to adapt it for WPF 4.

Kent Boogaart
  • 175,602
  • 35
  • 392
  • 393
  • I don't see how you would return more than one Key using that type. Something like CTRL+R wouldn't be possible in a single value. – Kyeotic Nov 01 '11 at 22:08
  • Sorry, misunderstood your question. Edited my post. – Kent Boogaart Nov 02 '11 at 08:34
  • I think you still misunderstand. I am not asking for multiple keystrokes, but modified keys. Ctrl+R is one key, as far as windows is concerned. – Kyeotic Nov 02 '11 at 17:46