WPF Commands, How to declare Application level commands?

后端 未结 5 672
不思量自难忘°
不思量自难忘° 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:21

    You can setup CommandBindings for "All Windows" of your WPF application and implement command handlers in Application class.

    First of all, create a static command container class. For example,

    namespace WpfApplication1 
    {
        public static class MyCommands
        {
            private static readonly RoutedUICommand doSomethingCommand = new RoutedUICommand("description", "DoSomethingCommand", typeof(MyCommands));
    
            public static RoutedUICommand DoSomethingCommand
            {
                get
                {
                    return doSomethingCommand;
                }
            }
        }
    }
    

    Next, set your custom command to Button.Command like this.

    
        
            ...
            
        
    
    

    Finally, implement the command handler of your custom command in Application class.

    namespace WpfApplication1 
    {
    
        public partial class App : Application
        {
            public App()
            {
                var binding = new CommandBinding(MyCommands.DoSomethingCommand, DoSomething, CanDoSomething);
    
                // Register CommandBinding for all windows.
                CommandManager.RegisterClassCommandBinding(typeof(Window), binding);
            }
    
            private void DoSomething(object sender, ExecutedRoutedEventArgs e)
            {
                ...
            }
    
            private void CanDoSomething(object sender, CanExecuteRoutedEventArgs e)
            {
                ...
                e.CanExecute = true;
            }
        }
    }
    

提交回复
热议问题