// -------------------------------------------------------------------------------------------------------------------- // // This file is part of the HandBrake source code - It may be used under the terms of the GNU General Public License. // // // Defines the MenuItemExtensions type. // // -------------------------------------------------------------------------------------------------------------------- namespace HandBrakeWPF.AttachedProperties { using System; using System.Collections.Generic; using System.Windows; using System.Windows.Controls; /// /// The menu item extensions. /// public class MenuItemExtensions : DependencyObject { #region Constants and Fields /// /// The group name property. /// public static readonly DependencyProperty GroupNameProperty = DependencyProperty.RegisterAttached( "GroupName", typeof(string), typeof(MenuItemExtensions), new PropertyMetadata(String.Empty, OnGroupNameChanged)); /// /// The element to group names. /// public static Dictionary ElementToGroupNames = new Dictionary(); #endregion #region Public Methods /// /// The get group name. /// /// /// The element. /// /// /// The group name as a string. /// public static string GetGroupName(MenuItem element) { return element.GetValue(GroupNameProperty).ToString(); } /// /// The set group name. /// /// /// The element. /// /// /// The value. /// public static void SetGroupName(MenuItem element, string value) { element.SetValue(GroupNameProperty, value); } #endregion #region Methods /// /// The menu item checked. /// /// /// The sender. /// /// /// The e. /// 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; } } } /// /// The on group name changed. /// /// /// The d. /// /// /// The e. /// private static void OnGroupNameChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { MenuItem menuItem = d as MenuItem; if (menuItem != null) { string newGroupName = e.NewValue.ToString(); string oldGroupName = e.OldValue.ToString(); if (string.IsNullOrEmpty(newGroupName)) { RemoveCheckboxFromGrouping(menuItem); } else { if (newGroupName != oldGroupName) { if (!string.IsNullOrEmpty(oldGroupName)) { RemoveCheckboxFromGrouping(menuItem); } ElementToGroupNames.Add(menuItem, e.NewValue.ToString()); menuItem.Checked += MenuItemChecked; } } } } /// /// The remove checkbox from grouping. /// /// /// The check box. /// private static void RemoveCheckboxFromGrouping(MenuItem checkBox) { ElementToGroupNames.Remove(checkBox); checkBox.Checked -= MenuItemChecked; } #endregion } }