WPF Commands, How to declare Application level commands?

后端 未结 5 684
不思量自难忘°
不思量自难忘° 2020-12-09 03:41

I\'m interested in creating commands that are available from anywhere in my WPF application.

I\'d like them to work in the same way as Cut, Copy

5条回答
  •  半阙折子戏
    2020-12-09 04:24

    I did not like the complexity of the other solutions, but after a few hours of research I found out it is really simple.

    First setup your command as you usually do, but add a static property for WPF so that it can obtain an instance of your command.

    class MyCommand : ICommand
    {
        // Singleton for the simple cases, may be replaced with your own factory     
        public static ICommand Instance { get; } = new MyCommand();
    
        public bool CanExecute(object parameter)
        {
            return true; // TODO: Implement
        }
    
        public event EventHandler CanExecuteChanged;
    
        public void Execute(object parameter)
        {
            // TODO: Implement       
        }   
    }
    

    Add a reference to the namespace of your command in your XAML (last line), like this:

         
    

    Then just reference your static property in your XAML like this:

提交回复
热议问题