Use EventTrigger on a specific key

后端 未结 3 1066
无人共我
无人共我 2021-02-07 14:05

I would like to invoke a command using EventTrigger when a particular key is touched (for example, the spacebar key)

Currently I have:

  

        
3条回答
  •  面向向阳花
    2021-02-07 14:27

    I like the idea with a custom trigger but I didn't managed to make it work (some methods were changed or deprecated therefore the showed above definition of the SpaceKeyDownEventTrigger is not compiled now). So, I put here the working version with custom RoutedEvent instead. The SpaceKeyDownEvent is defined in MyControl custom control and is raised from the OnKeyDown method when an unhandled KeyDown attached event reaches MyControl and the key pressed is the spacebar.

    public class MyControl : ContentControl
    {
        // This constructor is provided automatically if you
        // add a Custom Control (WPF) to your project
        static MyControl()
        {
            DefaultStyleKeyProperty.OverrideMetadata(
                typeof(MyControl),
                new FrameworkPropertyMetadata(typeof(MyControl)));
        }
    
        // Create a custom routed event by first registering a RoutedEventID
        // This event uses the bubbling routing strategy
        public static readonly RoutedEvent SpaceKeyDownEvent = EventManager.RegisterRoutedEvent(
            "SpaceKeyDown",
            RoutingStrategy.Bubble,
            typeof(RoutedEventHandler),
            typeof(MyControl));
    
        // Provide CLR accessors for the event
        public event RoutedEventHandler SpaceKeyDown
        {
            add { AddHandler(SpaceKeyDownEvent, value); }
            remove { RemoveHandler(SpaceKeyDownEvent, value); }
        }
    
        // This method raises the SpaceKeyDown event
        protected virtual void RaiseSpaceKeyDownEvent()
        {
            RoutedEventArgs args = new RoutedEventArgs(SpaceKeyDownEvent);
            RaiseEvent(args);
        }
    
        // Here KeyDown attached event is customized for the desired key
        protected override void OnKeyDown(KeyEventArgs e)
        {
            base.OnKeyDown(e);
    
            if (e.Key == Key.Space)
                RaiseSpaceKeyDownEvent();
        }
    }
    

    The MyControl could be added to the template of another control, allowing the latter to use EventTrigger with the SpaceKeyDown routed event:

    
    
        
        
    

提交回复
热议问题