ListBoxAttach.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using System.Collections;
  2. using System.Linq;
  3. using System.Windows;
  4. using System.Windows.Controls;
  5. using HandyControl.Data;
  6. namespace HandyControl.Controls;
  7. public class ListBoxAttach
  8. {
  9. public static readonly DependencyProperty SelectedItemsProperty = DependencyProperty.RegisterAttached(
  10. "SelectedItems", typeof(IList), typeof(ListBoxAttach),
  11. new FrameworkPropertyMetadata(default(IList), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
  12. OnSelectedItemsChanged));
  13. public static void SetSelectedItems(DependencyObject element, IList value)
  14. => element.SetValue(SelectedItemsProperty, value);
  15. public static IList GetSelectedItems(DependencyObject element)
  16. => (IList) element.GetValue(SelectedItemsProperty);
  17. internal static readonly DependencyProperty InternalActionProperty = DependencyProperty.RegisterAttached(
  18. "InternalAction", typeof(bool), typeof(ListBoxAttach), new PropertyMetadata(ValueBoxes.FalseBox));
  19. internal static void SetInternalAction(DependencyObject element, bool value)
  20. => element.SetValue(InternalActionProperty, ValueBoxes.BooleanBox(value));
  21. internal static bool GetInternalAction(DependencyObject element)
  22. => (bool) element.GetValue(InternalActionProperty);
  23. private static void OnSelectedItemsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  24. {
  25. if (d is not ListBox listBox)
  26. {
  27. return;
  28. }
  29. if (GetInternalAction(listBox))
  30. {
  31. return;
  32. }
  33. listBox.SelectionChanged -= OnListBoxSelectionChanged;
  34. listBox.SelectedItems.Clear();
  35. if (e.NewValue is IList selectedItems)
  36. {
  37. foreach (object selectedItem in selectedItems)
  38. {
  39. listBox.SelectedItems.Add(selectedItem);
  40. }
  41. }
  42. listBox.SelectionChanged += OnListBoxSelectionChanged;
  43. }
  44. private static void OnListBoxSelectionChanged(object sender, SelectionChangedEventArgs e)
  45. {
  46. if (sender is ListBox listBox)
  47. {
  48. SetInternalAction(listBox, true);
  49. SetSelectedItems(listBox, listBox.SelectedItems.Cast<object>().ToArray());
  50. SetInternalAction(listBox, false);
  51. }
  52. }
  53. }