The UserControl dynamically loaded to the ContentControl in my Window does not receive keyboard shortcuts defined inside of UserControl XAML, in case it is not focused.
I need to implement keyboard shortcuts for dynamically loaded UserControl, without focusing the UserControl.
I cannot define InputBindings on MainWindow, because the InputBindigs are changing depends on currently loaded UserControl.
1) So I tried to send all Window_KeyUp to the loaded UserControl via RaiseEvent, no luck. (StackOverflow Exception or no action called)
2) I tried also fillup the MainWindow.InputBindings by LoadedUserControl.InputBindings when the UserControl has been loaded to the ContentControl... no luck (defined command is unknown in context)
UserControl.xaml
----------------
<UserControl.InputBindings>
<KeyBinding Key="N" Command="{Binding Path=NewOrderCommand}" Modifiers="Control" />
</UserControl.InputBindings>
This is working if UserControl is focused.
So to get rid of focusing I tried this:
MainWindow.xaml.cs
-------------------
private void MainWindow_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
{
// ModulePanel points to the loaded UserControl
ViewModel.CurrentModule.ModulePanel.RaiseEvent(e);
e.Handled = true;
}
So this issued StackOverflowException
I tried set e.Handled = true; before RaiseEvent(e) but it does not pass the event to the UserControl - so nothing happens;
I also tried to get InputBindings from UserControl to MainWindow:
foreach(InputBinding bi in UserControl.InputBindings)
MainWindow.InputBindings.Add(bi);
But I got exception in Debug window:
Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=NewOrderCommand; DataItem=null; target element is 'KeyBinding' (HashCode=35527846); target property is 'Command' (type 'ICommand')
My expectation is, that I will dynamically change Window InputBindings depends on loaded UserControl, where the InputBindings are defined.
If you want the UserControl
to be able to handle all key presses in the window, you could get a reference to the parent window using the Window.GetWindow
once the UserControl
has been loaded and then hook up an event handler to it:
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
Loaded += (s, e) =>
{
Window parentWindow = Window.GetWindow(this);
parentWindow.PreviewKeyDown += ParentWindow_PreviewKeyDown;
};
Unloaded += (s, e) =>
{
Window parentWindow = Window.GetWindow(this);
parentWindow.PreviewKeyDown -= ParentWindow_PreviewKeyDown;
};
}
private void ParentWindow_PreviewKeyDown(object sender, KeyEventArgs e)
{
//do something...
}
}