ContextMenuStrip.xaml.cs 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. using System.ComponentModel;
  2. using System.Windows.Controls;
  3. namespace CustomControls
  4. {
  5. [DesignTimeVisible(false)]
  6. public partial class ContextMenuStrip : ContextMenu
  7. {
  8. public ContextMenuStrip()
  9. {
  10. InitializeComponent();
  11. }
  12. public bool EnableQuickAccessToolbar { get; set; }
  13. public void SetIsOpen(bool value)
  14. {
  15. if (value && EnableQuickAccessToolbar)
  16. MakeToolbarItems();
  17. IsOpen = value;
  18. }
  19. private void RemoveDuplicateSeparators(ItemCollection items)
  20. {
  21. for (int i = 1; i < items.Count; i++)
  22. {
  23. var item = items[i];
  24. if (item is Separator)
  25. {
  26. // check if previous item is not separator
  27. var previousItem = items[i - 1];
  28. if (previousItem is Separator)
  29. {
  30. items.RemoveAt(i);
  31. i--;
  32. }
  33. }
  34. }
  35. }
  36. private void TrimSeparators(ItemCollection items)
  37. {
  38. if (items.Count > 0 && items[0] is Separator)
  39. items.RemoveAt(0);
  40. if (items.Count > 0 && items[items.Count - 1] is Separator)
  41. items.RemoveAt(items.Count - 1);
  42. }
  43. private ToolStripButton CreateToolbarButton(System.Windows.Forms.ToolStripMenuItem swfMenuItem)
  44. {
  45. var button = new ToolStripButton() { Width = 22, Height = 22 };
  46. button.Image = swfMenuItem.ImageSource;
  47. button.ToolTip = swfMenuItem.Text;
  48. button.IsEnabled = swfMenuItem.Enabled;
  49. button.Click += (s, e) =>
  50. {
  51. swfMenuItem.OnItemClicked();
  52. IsOpen = false;
  53. };
  54. return button;
  55. }
  56. private void MakeToolbarItems()
  57. {
  58. ApplyTemplate();
  59. var toolBar = Template.FindName("ToolBar", this) as ToolStrip;
  60. // put items with QatItem = true in the quick access toolbar
  61. if (toolBar != null)
  62. {
  63. toolBar.Items.Clear();
  64. for (int i = 0; i < this.Items.Count; i++)
  65. {
  66. var item = this.Items[i];
  67. if (item is ToolStripMenuItem menuItem)
  68. {
  69. var swfMenuItem = menuItem.Tag as System.Windows.Forms.ToolStripMenuItem;
  70. if (swfMenuItem != null && swfMenuItem.QatItem)
  71. {
  72. // add visible items to toolbar
  73. if (swfMenuItem.Visible)
  74. toolBar.Items.Add(CreateToolbarButton(swfMenuItem));
  75. this.Items.RemoveAt(i);
  76. i--;
  77. }
  78. }
  79. else if (item is Separator)
  80. {
  81. toolBar.Items.Add(new Separator() { Margin = new System.Windows.Thickness(4) });
  82. }
  83. }
  84. RemoveDuplicateSeparators(this.Items);
  85. RemoveDuplicateSeparators(toolBar.Items);
  86. TrimSeparators(this.Items);
  87. TrimSeparators(toolBar.Items);
  88. if (toolBar.Items.Count > 0)
  89. VerticalOffset -= 30;
  90. }
  91. }
  92. }
  93. }