WPF allows me to easily bind keyboard shortcuts at the window level to a method using the InputBindings property. What is the equivalent of this in WinRT? What is the right way to bind keyboard shortcuts to methods in WinRT?
Keyboard shortcuts are described here. I think you want either access keys or accelerator keys.
An access key is a shortcut to a piece of UI in your app. Access keys consist of the Alt key plus a letter key.
An accelerator key is a shortcut to an app command. Your app may or may not have UI that corresponds exactly to the command. Accelerator keys consist of the Ctrl key plus a letter key.
The following example demonstrates the accessible implementation of shortcut keys for media play, pause, and stop buttons:
<MediaElement x:Name="Movie" Source="sample.wmv"
AutoPlay="False" Width="320" Height="240"/>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
<Button x:Name="Play" Margin="1,2"
ToolTipService.ToolTip="shortcut key: Ctrl+P"
AutomationProperties.AccessKey="Control P">
<TextBlock><Underline>P</Underline>lay</TextBlock>
</Button>
<Button x:Name="Pause" Margin="1,2"
ToolTipService.ToolTip="shortcut key: Ctrl+A"
AutomationProperties.AccessKey="Control A">
<TextBlock>P<Underline>a</Underline>use</TextBlock>
</Button>
<Button x:Name="Stop" Margin="1,2"
ToolTipService.ToolTip="shortcut key: Ctrl+S"
AutomationProperties.AccessKey="Control S">
<TextBlock><Underline>S</Underline>top</TextBlock>
</Button>
</StackPanel>
<object AutomationProperties.AcceleratorKey="ALT+F" />
See @Magiel's answer for implementation details for the code-side of things.
Important!! Setting AutomationProperties.AcceleratorKey or AutomationProperties.AccessKey doesn't enable keyboard functionality. It only reports to the UI Automation framework what keys should be used, so that such information can be passed on to users via assistive technologies. The implementation for key handling still needs to be done in code, not XAML.
protected override void OnNavigatedTo(NavigationEventArgs e)
{
// Set the input focus to ensure that keyboard events are raised.
this.Loaded += delegate { this.Focus(FocusState.Programmatic); };
}
private void Grid_KeyUp(object sender, KeyRoutedEventArgs e)
{
if (e.Key == VirtualKey.Control) isCtrlKeyPressed = false;
}
private void Grid_KeyDown(object sender, KeyRoutedEventArgs e)
{
if (e.Key == VirtualKey.Control) isCtrlKeyPressed = true;
else if (isCtrlKeyPressed)
{
switch (e.Key)
{
case VirtualKey.P: DemoMovie.Play(); break;
case VirtualKey.A: DemoMovie.Pause(); break;
case VirtualKey.S: DemoMovie.Stop(); break;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With