using System; using System.Collections.Generic; using System.Windows; using System.Windows.Controls; namespace MultiTerm.Wpf.Controls { /// /// TODO ueberarbeiten /// FROM: /// https://stackoverflow.com/questions/3652688/mutually-exclusive-checkable-menu-items/11497189#11497189 /// public class MenuItemExtensions : MenuItem { private static MenuItem? previouslySelectedMenuItem = null; public static Dictionary ElementToGroupNames = new Dictionary(); public static readonly DependencyProperty GroupNameProperty = DependencyProperty.RegisterAttached("GroupName", typeof(String), typeof(MenuItemExtensions), new PropertyMetadata(String.Empty, OnGroupNameChanged)); public static readonly RoutedEvent IsCheckedChangedEvent = EventManager.RegisterRoutedEvent("IsCheckedChanged", RoutingStrategy.Bubble, typeof(RoutedEventArgs), typeof(MenuItemExtensions)); public event RoutedEventHandler IsCheckedChanged { add { this.AddHandler(IsCheckedChangedEvent, value); } remove { this.RemoveHandler(IsCheckedChangedEvent, value); } } 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 var menuItem = d as MenuItem; var parent = menuItem.Parent as MenuItem; if (menuItem != null) { String newGroupName = e.NewValue.ToString(); String 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) { if (!String.IsNullOrEmpty(oldGroupName)) { //Remove the old group mapping RemoveCheckboxFromGrouping(menuItem); } ElementToGroupNames.Add(menuItem, e.NewValue.ToString()); menuItem.IsCheckable = true; menuItem.Checked += MenuItemChecked; } } } } private static void RemoveCheckboxFromGrouping(MenuItem checkBox) { ElementToGroupNames.Remove(checkBox); checkBox.Checked -= MenuItemChecked; } static void MenuItemChecked(object sender, RoutedEventArgs e) { var menuItem = e.OriginalSource as MenuItem; foreach (var item in ElementToGroupNames) { // uncheck all other menu items in group if (item.Key != menuItem && item.Value == GetGroupName(menuItem)) { item.Key.IsChecked = false; } } // raise routed event var menuItemExtensions = menuItem as MenuItemExtensions; if(previouslySelectedMenuItem != null && previouslySelectedMenuItem != menuItem) { RoutedEventArgs args = new RoutedEventArgs(IsCheckedChangedEvent); menuItemExtensions.RaiseEvent(args); } previouslySelectedMenuItem = menuItem; } } }