3using System.Windows.Input;
4using System.Windows.Media;
12 public static class ListBoxGlobalSingleSelectionBehavior
14 private static readonly HashSet<ListBox> _globalSingleSelectionListBoxes =
new();
15 private static bool _isUpdatingSelection;
17 public static readonly DependencyProperty IsEnabledProperty = DependencyProperty.RegisterAttached(
"IsEnabled", typeof(
bool), typeof(ListBoxGlobalSingleSelectionBehavior),
new PropertyMetadata(
false, OnIsEnabledChanged));
19 public static void SetIsEnabled(DependencyObject element,
bool value)
20 => element.SetValue(IsEnabledProperty, value);
22 public static bool GetIsEnabled(DependencyObject element)
23 => (bool)element.GetValue(IsEnabledProperty);
25 private static void OnIsEnabledChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
27 if (d is ListBox listBox)
31 if (_globalSingleSelectionListBoxes.Add(listBox))
33 listBox.AddHandler(UIElement.PreviewMouseDownEvent,
new MouseButtonEventHandler(OnPreviewMouseDown),
true);
38 if (_globalSingleSelectionListBoxes.Remove(listBox))
40 listBox.RemoveHandler(UIElement.PreviewMouseDownEvent,
new MouseButtonEventHandler(OnPreviewMouseDown));
46 private static void OnPreviewMouseDown(
object sender, MouseButtonEventArgs e)
48 if (_isUpdatingSelection)
52 ListBoxItem sourceItem = FindParent<ListBoxItem>(e.OriginalSource as DependencyObject);
53 if (sourceItem ==
null)
57 ListBox sourceList = FindParent<ListBox>(sourceItem);
58 if (sourceList ==
null || !_globalSingleSelectionListBoxes.Contains(sourceList))
63 _isUpdatingSelection =
true;
66 foreach (ListBox listBox
in _globalSingleSelectionListBoxes.Where(l => l != sourceList))
68 if (listBox.SelectedItem !=
null)
70 listBox.SelectedItem =
null;
76 _isUpdatingSelection =
false;
80 private static T FindParent<T>(DependencyObject element) where T : DependencyObject
82 while (element !=
null && element is not T)
84 element = VisualTreeHelper.GetParent(element);