ContextMenu.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. using PixiEditor.Helpers;
  2. using PixiEditor.Models.DataHolders;
  3. using System.ComponentModel;
  4. using System.Windows;
  5. using System.Windows.Controls;
  6. namespace PixiEditor.Models.Commands.XAML
  7. {
  8. public class ContextMenu : System.Windows.Controls.ContextMenu
  9. {
  10. public static readonly DependencyProperty CommandNameProperty =
  11. DependencyProperty.RegisterAttached(
  12. "Command",
  13. typeof(string),
  14. typeof(ContextMenu),
  15. new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender, CommandChanged)
  16. );
  17. public static string GetCommand(UIElement target) => (string)target.GetValue(CommandNameProperty);
  18. public static void SetCommand(UIElement target, string value) => target.SetValue(CommandNameProperty, value);
  19. public static void CommandChanged(object sender, DependencyPropertyChangedEventArgs e)
  20. {
  21. if (e.NewValue is not string value || sender is not MenuItem item)
  22. {
  23. throw new InvalidOperationException($"{nameof(ContextMenu)}.Command only works for MenuItem's");
  24. }
  25. if (DesignerProperties.GetIsInDesignMode(sender as DependencyObject))
  26. {
  27. HandleDesignMode(item, value);
  28. return;
  29. }
  30. var command = CommandController.Current.Commands[value];
  31. item.Command = Command.GetICommand(command, false);
  32. item.SetBinding(MenuItem.InputGestureTextProperty, ShortcutBinding.GetBinding(command));
  33. }
  34. private static void HandleDesignMode(MenuItem item, string name)
  35. {
  36. var command = DesignCommandHelpers.GetCommandAttribute(name);
  37. item.InputGestureText = new KeyCombination(command.Key, command.Modifiers).ToString();
  38. }
  39. }
  40. }