-
Notifications
You must be signed in to change notification settings - Fork 294
/
MenuItemGroup.cs
81 lines (71 loc) · 2.77 KB
/
MenuItemGroup.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
namespace Rubberduck.UI.Controls
{
/// <summary>
/// Thanks to @Patrick at http://stackoverflow.com/a/3652980/1188513
/// </summary>
public class MenuItemGroup : DependencyObject
{
private static readonly Dictionary<MenuItem, string> ElementToGroupNames = new Dictionary<MenuItem, string>();
public static readonly DependencyProperty GroupNameProperty =
DependencyProperty.RegisterAttached("GroupName",
typeof(string),
typeof(MenuItemGroup),
new PropertyMetadata(string.Empty, OnGroupNameChanged));
public static void SetGroupName(MenuItem element, string value)
{
element.SetValue(GroupNameProperty, value);
}
public static string GetGroupName(MenuItem element)
{
return element.GetValue(GroupNameProperty).ToString();
}
private static void OnGroupNameChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
//Add an entry to the group name collection
if (d is MenuItem menuItem)
{
var newGroupName = e.NewValue.ToString();
var oldGroupName = e.OldValue.ToString();
if (string.IsNullOrEmpty(newGroupName))
{
//Removing the toggle button from grouping
RemoveCheckboxFromGrouping(menuItem);
}
else
{
//Switching to a new group
if (newGroupName == oldGroupName)
{
return;
}
if (!string.IsNullOrEmpty(oldGroupName))
{
//Remove the old group mapping
RemoveCheckboxFromGrouping(menuItem);
}
ElementToGroupNames.Add(menuItem, e.NewValue.ToString());
menuItem.Checked += MenuItemChecked;
}
}
}
private static void RemoveCheckboxFromGrouping(MenuItem checkBox)
{
ElementToGroupNames.Remove(checkBox);
checkBox.Checked -= MenuItemChecked;
}
private static void MenuItemChecked(object sender, RoutedEventArgs e)
{
var menuItem = e.OriginalSource as MenuItem;
foreach (var item in ElementToGroupNames)
{
if (item.Key != menuItem && item.Value == GetGroupName(menuItem))
{
item.Key.IsChecked = false;
}
}
}
}
}