Skip to content

Instantly share code, notes, and snippets.

@SuperJMN
Created May 5, 2017 11:01
Show Gist options
  • Save SuperJMN/170e7487f934b924cad6ed84032771e4 to your computer and use it in GitHub Desktop.
Save SuperJMN/170e7487f934b924cad6ed84032771e4 to your computer and use it in GitHub Desktop.
A Trigger that executes Actions when a KeyDown event occurs.
using System;
using System.Reactive.Linq;
using Windows.System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Input;
using Microsoft.Xaml.Interactivity;
namespace App2
{
public class KeyTrigger : Trigger
{
private IDisposable actionExecutor;
protected override void OnAttached()
{
var fe = (FrameworkElement)AssociatedObject;
var keyObs = Observable
.FromEventPattern<KeyEventHandler, KeyRoutedEventArgs>(
handler => fe.KeyDown += handler,
handler => fe.KeyDown -= handler);
actionExecutor = keyObs
.Where(pattern => pattern.EventArgs.Key == Key)
.Subscribe(d =>
{
d.EventArgs.Handled = true;
Interaction.ExecuteActions(this, Actions, null);
});
}
protected override void OnDetaching()
{
actionExecutor?.Dispose();
}
public VirtualKey Key { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment