PopupHelper.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. using System.Runtime.InteropServices;
  6. using System.Text;
  7. using System.Windows;
  8. using System.Windows.Controls.Primitives;
  9. using System.Windows.Interop;
  10. namespace CustomUI
  11. {
  12. /// <summary>
  13. /// Popup帮助类,解决Popup设置StayOpen="True"时,移动窗体或者改变窗体大小时,Popup不随窗体移动的问题
  14. /// </summary>
  15. public class PopopHelper
  16. {
  17. #region PopupPlacementTarget
  18. public static DependencyObject GetPopupPlacementTarget(DependencyObject obj)
  19. {
  20. return (DependencyObject)obj.GetValue(PopupPlacementTargetProperty);
  21. }
  22. public static void SetPopupPlacementTarget(DependencyObject obj, DependencyObject value)
  23. {
  24. obj.SetValue(PopupPlacementTargetProperty, value);
  25. }
  26. public static readonly DependencyProperty PopupPlacementTargetProperty =
  27. DependencyProperty.RegisterAttached("PopupPlacementTarget", typeof(DependencyObject), typeof(PopopHelper), new PropertyMetadata(null, OnPopupPlacementTargetChanged));
  28. private static void OnPopupPlacementTargetChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  29. {
  30. if (e.NewValue != null)
  31. {
  32. DependencyObject popupPopupPlacementTarget = e.NewValue as DependencyObject;
  33. Popup pop = d as Popup;
  34. Window w = Window.GetWindow(popupPopupPlacementTarget);
  35. if (null != w)
  36. {
  37. //让Popup随着窗体的移动而移动
  38. w.LocationChanged += delegate
  39. {
  40. UpdatePosition(pop);
  41. };
  42. //让Popup随着窗体的Size改变而移动位置
  43. w.SizeChanged += delegate
  44. {
  45. UpdatePosition(pop);
  46. };
  47. }
  48. }
  49. }
  50. #endregion
  51. private static void UpdatePosition(Popup pop)
  52. {
  53. if(pop == null)
  54. {
  55. return;
  56. }
  57. var offset = pop.HorizontalOffset;
  58. pop.HorizontalOffset = offset + 1;
  59. pop.HorizontalOffset = offset;
  60. //MethodInfo mi = typeof(Popup).GetMethod("UpdatePosition", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
  61. //try
  62. //{
  63. // if(mi != null)
  64. // {
  65. // mi.Invoke(pop, null);
  66. // }
  67. //}
  68. //catch (Exception ex)
  69. //{
  70. // System.Diagnostics.Debug.WriteLine(ex.Message);
  71. //}
  72. }
  73. }
  74. }