How can I bind key gestures in Caliburn.Micro?

前端 未结 5 1300
一个人的身影
一个人的身影 2020-12-30 08:47

How can I get Caliburn.Micro to map a key gesture to an action method on my ViewModel?

For example, I want to implement a tabbed interface, and I want my ShellViewMo

5条回答
  •  死守一世寂寞
    2020-12-30 09:37

    I modified example to enable support for global key-bindings. You just need to add the folowing code to your view:

    
            
                
                    
                
                
            
        
    

    And whenever Ctr+D is pressed the method DoTheMagic will be exexuted. Here is the modified InputBindingTrigger code:

    public class InputBindingTrigger : TriggerBase, ICommand
      {
        public static readonly DependencyProperty InputBindingProperty =
          DependencyProperty.Register("InputBinding", typeof (InputBinding)
            , typeof (InputBindingTrigger)
            , new UIPropertyMetadata(null));
    
        public InputBinding InputBinding
        {
          get { return (InputBinding) GetValue(InputBindingProperty); }
          set { SetValue(InputBindingProperty, value); }
        }
    
        public event EventHandler CanExecuteChanged = delegate { };
    
        public bool CanExecute(object parameter)
        {
          // action is anyway blocked by Caliburn at the invoke level
          return true;
        }
    
        public void Execute(object parameter)
        {
          InvokeActions(parameter);
        }
    
        protected override void OnAttached()
        {
          if (InputBinding != null)
          {
            InputBinding.Command = this;        
            AssociatedObject.Loaded += delegate {
              var window = GetWindow(AssociatedObject);
              window.InputBindings.Add(InputBinding);
            };
          }
          base.OnAttached();
        }
    
        private Window GetWindow(FrameworkElement frameworkElement)
        {
          if (frameworkElement is Window)
            return frameworkElement as Window;
    
          var parent = frameworkElement.Parent as FrameworkElement;      
          Debug.Assert(parent != null);
    
          return GetWindow(parent);
        }
      }
    

提交回复
热议问题