code_junkie

I don't grok the WPF command pattern

Nov 10th, 2011
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.64 KB | None | 0 0
  1. public static class CommandBank
  2. {
  3. /// Command definition for Closing a window
  4. public static RoutedUICommand CloseWindow { get; private set; }
  5.  
  6. /// Static private constructor, sets up all application wide commands.
  7. static CommandBank()
  8. {
  9. CloseWindow = new RoutedUICommand();
  10. CloseWindow.InputGestures.Add(new KeyGesture(Key.F4, ModifierKeys.Alt));
  11. // ...
  12. }
  13.  
  14. /// Closes the window provided as a parameter
  15. public static void CloseWindowExecute(object sender, ExecutedRoutedEventArgs e)
  16. {
  17. ((Window)e.Parameter).Close();
  18. }
  19.  
  20. /// Allows a Command to execute if the CommandParameter is not a null value
  21. public static void CanExecuteIfParameterIsNotNull(object sender, CanExecuteRoutedEventArgs e)
  22. {
  23. e.CanExecute = e.Parameter != null;
  24. e.Handled = true;
  25. }
  26.  
  27. public partial class SimpleWindow : Window
  28. {
  29. private void WindowLoaded(object sender, RoutedEventArgs e)
  30. {
  31. // ...
  32. this.CommandBindings.Add(
  33. new CommandBinding(
  34. CommandBank.CloseWindow,
  35. CommandBank.CloseWindowExecute,
  36. CommandBank.CanExecuteIfParameterIsNotNull));
  37.  
  38. foreach (CommandBinding binding in this.CommandBindings)
  39. {
  40. RoutedCommand command = (RoutedCommand)binding.Command;
  41. if (command.InputGestures.Count > 0)
  42. {
  43. foreach (InputGesture gesture in command.InputGestures)
  44. {
  45. var iBind = new InputBinding(command, gesture);
  46. iBind.CommandParameter = this;
  47. this.InputBindings.Add(iBind);
  48. }
  49. }
  50. }
  51.  
  52. // menuItemExit is defined in XAML
  53. menuItemExit.Command = CommandBank.CloseWindow;
  54. menuItemExit.CommandParameter = this;
  55. // ...
  56. }
  57.  
  58. // ....
  59. }
Add Comment
Please, Sign In to add comment