MenuItemAttach.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. using System.Linq;
  2. using System.Windows;
  3. using System.Windows.Controls;
  4. using HandyControl.Tools.Extension;
  5. namespace HandyControl.Controls;
  6. public class MenuItemAttach
  7. {
  8. public static readonly DependencyProperty GroupNameProperty =
  9. DependencyProperty.RegisterAttached("GroupName", typeof(string), typeof(MenuItemAttach),
  10. new PropertyMetadata(string.Empty, OnGroupNameChanged));
  11. [AttachedPropertyBrowsableForType(typeof(MenuItem))]
  12. public static string GetGroupName(DependencyObject obj) => (string) obj.GetValue(GroupNameProperty);
  13. [AttachedPropertyBrowsableForType(typeof(MenuItem))]
  14. public static void SetGroupName(DependencyObject obj, string value) => obj.SetValue(GroupNameProperty, value);
  15. private static void OnGroupNameChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  16. {
  17. if (d is not MenuItem menuItem)
  18. {
  19. return;
  20. }
  21. menuItem.Checked -= MenuItem_Checked;
  22. menuItem.Click -= MenuItem_Click;
  23. if (string.IsNullOrWhiteSpace(e.NewValue.ToString()))
  24. {
  25. return;
  26. }
  27. menuItem.Checked += MenuItem_Checked;
  28. menuItem.Click += MenuItem_Click;
  29. }
  30. private static void MenuItem_Checked(object sender, RoutedEventArgs e)
  31. {
  32. if (sender is not MenuItem { Parent: MenuItem parent } menuItem)
  33. {
  34. return;
  35. }
  36. var groupName = GetGroupName(menuItem);
  37. parent
  38. .Items
  39. .OfType<MenuItem>()
  40. .Where(item => item != menuItem && item.IsCheckable && string.Equals(GetGroupName(item), groupName))
  41. .Do(item => item.IsChecked = false);
  42. }
  43. private static void MenuItem_Click(object sender, RoutedEventArgs e)
  44. {
  45. // prevent uncheck when click the checked menu item
  46. if (e.OriginalSource is MenuItem { IsChecked: false } menuItem)
  47. {
  48. menuItem.IsChecked = true;
  49. }
  50. }
  51. }