Vereinsmeisterschaften  22aa7800eae54b428d40e835886cefe1fdefdfdf
This is a software that can be used to manage the internal competition of the swimming club Illertissen called "Vereinsmeisterschaften".
Loading...
Searching...
No Matches
ListBoxGlobalSingleSelectionBehavior.cs
3using System.Windows.Input;
4using System.Windows.Media;
5
7{
12 public static class ListBoxGlobalSingleSelectionBehavior
13 {
14 private static readonly HashSet<ListBox> _globalSingleSelectionListBoxes = new();
15 private static bool _isUpdatingSelection;
16
17 public static readonly DependencyProperty IsEnabledProperty = DependencyProperty.RegisterAttached("IsEnabled", typeof(bool), typeof(ListBoxGlobalSingleSelectionBehavior), new PropertyMetadata(false, OnIsEnabledChanged));
18
19 public static void SetIsEnabled(DependencyObject element, bool value)
20 => element.SetValue(IsEnabledProperty, value);
21
22 public static bool GetIsEnabled(DependencyObject element)
23 => (bool)element.GetValue(IsEnabledProperty);
24
25 private static void OnIsEnabledChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
26 {
27 if (d is ListBox listBox)
28 {
29 if ((bool)e.NewValue)
30 {
31 if (_globalSingleSelectionListBoxes.Add(listBox))
32 {
33 listBox.AddHandler(UIElement.PreviewMouseDownEvent, new MouseButtonEventHandler(OnPreviewMouseDown), true);
34 }
35 }
36 else
37 {
38 if (_globalSingleSelectionListBoxes.Remove(listBox))
39 {
40 listBox.RemoveHandler(UIElement.PreviewMouseDownEvent, new MouseButtonEventHandler(OnPreviewMouseDown));
41 }
42 }
43 }
44 }
45
46 private static void OnPreviewMouseDown(object sender, MouseButtonEventArgs e)
47 {
48 if (_isUpdatingSelection)
49 return;
50
51 // Check if the click was on a ListBoxItem
52 ListBoxItem sourceItem = FindParent<ListBoxItem>(e.OriginalSource as DependencyObject);
53 if (sourceItem == null)
54 return;
55
56 // Find the ListBox in which the click occurred
57 ListBox sourceList = FindParent<ListBox>(sourceItem);
58 if (sourceList == null || !_globalSingleSelectionListBoxes.Contains(sourceList))
59 return;
60
61 try
62 {
63 _isUpdatingSelection = true;
64
65 // Deselect all other lists before processing the click
66 foreach (ListBox listBox in _globalSingleSelectionListBoxes.Where(l => l != sourceList))
67 {
68 if (listBox.SelectedItem != null)
69 {
70 listBox.SelectedItem = null;
71 }
72 }
73 }
74 finally
75 {
76 _isUpdatingSelection = false;
77 }
78 }
79
80 private static T FindParent<T>(DependencyObject element) where T : DependencyObject
81 {
82 while (element != null && element is not T)
83 {
84 element = VisualTreeHelper.GetParent(element);
85 }
86 return element as T;
87 }
88 }
89}