WindowDragBehavior.cs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Windows;
  7. using System.Windows.Controls;
  8. namespace WpfStyleableWindow.StyleableWindow
  9. {
  10. public static class WindowDragBehavior
  11. {
  12. public static Window GetLeftMouseButtonDrag(DependencyObject obj)
  13. {
  14. return (Window)obj.GetValue(LeftMouseButtonDrag);
  15. }
  16. public static void SetLeftMouseButtonDrag(DependencyObject obj, Window window)
  17. {
  18. obj.SetValue(LeftMouseButtonDrag, window);
  19. }
  20. public static readonly DependencyProperty LeftMouseButtonDrag = DependencyProperty.RegisterAttached("LeftMouseButtonDrag",
  21. typeof(Window), typeof(WindowDragBehavior),
  22. new UIPropertyMetadata(null, OnLeftMouseButtonDragChanged));
  23. private static void OnLeftMouseButtonDragChanged(object sender, DependencyPropertyChangedEventArgs e)
  24. {
  25. var element = sender as UIElement;
  26. if (element != null)
  27. {
  28. element.MouseLeftButtonDown += buttonDown;
  29. }
  30. }
  31. private static void buttonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
  32. {
  33. var element = sender as UIElement;
  34. var targetWindow = element.GetValue(LeftMouseButtonDrag) as Window;
  35. if (targetWindow != null)
  36. {
  37. targetWindow.DragMove();
  38. }
  39. }
  40. }
  41. }