I have designed a reuseable usercontrol. It contains UserControl.InputBindings. It is quite simple as it only contains a label and a button (and new properties etc.)
Yes, UserControl KeyBindings will only work when the control has focus.
If you want the KeyBinding to work on the window, then you have to define it on the window itself. You do that on the Windows XAML using :
However you have said you want the UserControl to define the KeyBinding. I don't know of any way to do this in XAML, so you would have to set up this in the code-behind of the UserControl. That means finding the parent Window of the UserControl and creating the KeyBinding
{
var window = FindVisualAncestorOfType(this);
window.InputBindings.Add(new KeyBinding(ViewModel.ExecuteCommand, ViewModel.FunctionKey, ModifierKeys.None));
}
private T FindVisualAncestorOfType(DependencyObject d) where T : DependencyObject
{
for (var parent = VisualTreeHelper.GetParent(d); parent != null; parent = VisualTreeHelper.GetParent(parent)) {
var result = parent as T;
if (result != null)
return result;
}
return null;
}
The ViewModel.FunctionKey would need to be of type Key in this case, or else you'll need to convert from a string to type Key.
Having to do this in code-behind rather than XAML does not break the MVVM pattern. All that is being done is moving the binding logic from XAML to C#. The ViewModel is still independent of the View, and as such can be Unit Tested without instantiating the View. It is absolutely fine to put such UI specific logic in the code-behind of a view.