原文:Popup 解决位置不随窗口/元素FrameworkElement 移动更新的问题

Popup弹出后,因业务需求设置了StaysOpen=true后,移动窗口位置或者改变窗口大小,Popup的位置不会更新。

如何更新位置?

获取当前Popup的Target绑定UserControl所在窗口,位置刷新时,时时更新Popup的位置即可。

1.添加一个附加属性

 /// <summary>
/// Popup位置更新
/// </summary>
public static readonly DependencyProperty PopupPlacementTargetProperty =
DependencyProperty.RegisterAttached("PopupPlacementTarget", typeof(DependencyObject), typeof(PopupHelper), new PropertyMetadata(null, OnPopupPlacementTargetChanged));

2.窗口移动后触发popup更新

首先,有个疑问,popup首次显示时,为何显示的位置是正确的呢?

通过查看源码,发现,其实popup也是有内置更新popup位置的!

而通过查看UpdatePosition代码,其方法确实是更新popup位置的。源码如下:

 private void UpdatePosition()
{
if (this._popupRoot.Value == null)
return;
PlacementMode placement = this.Placement;
Point[] targetInterestPoints = this.GetPlacementTargetInterestPoints(placement);
Point[] childInterestPoints = this.GetChildInterestPoints(placement);
Rect bounds = this.GetBounds(targetInterestPoints);
Rect rect1 = this.GetBounds(childInterestPoints);
double num1 = rect1.Width * rect1.Height;
int num2 = -;
Vector offsetVector1 = new Vector((double)this._positionInfo.X, (double)this._positionInfo.Y);
double num3 = -1.0;
PopupPrimaryAxis popupPrimaryAxis = PopupPrimaryAxis.None;
CustomPopupPlacement[] customPopupPlacementArray = (CustomPopupPlacement[])null;
int num4;
if (placement == PlacementMode.Custom)
{
CustomPopupPlacementCallback placementCallback = this.CustomPopupPlacementCallback;
if (placementCallback != null)
customPopupPlacementArray = placementCallback(rect1.Size, bounds.Size, new Point(this.HorizontalOffset, this.VerticalOffset));
num4 = customPopupPlacementArray == null ? : customPopupPlacementArray.Length;
if (!this.IsOpen)
return;
}
else
num4 = Popup.GetNumberOfCombinations(placement);
for (int i = ; i < num4; ++i)
{
bool flag1 = false;
bool flag2 = false;
Vector offsetVector2;
PopupPrimaryAxis axis;
if (placement == PlacementMode.Custom)
{
offsetVector2 = (Vector)targetInterestPoints[] + (Vector)customPopupPlacementArray[i].Point;
axis = customPopupPlacementArray[i].PrimaryAxis;
}
else
{
Popup.PointCombination pointCombination = this.GetPointCombination(placement, i, out axis);
Popup.InterestPoint targetInterestPoint = pointCombination.TargetInterestPoint;
Popup.InterestPoint childInterestPoint = pointCombination.ChildInterestPoint;
offsetVector2 = targetInterestPoints[(int)targetInterestPoint] - childInterestPoints[(int)childInterestPoint];
flag1 = childInterestPoint == Popup.InterestPoint.TopRight || childInterestPoint == Popup.InterestPoint.BottomRight;
flag2 = childInterestPoint == Popup.InterestPoint.BottomLeft || childInterestPoint == Popup.InterestPoint.BottomRight;
}
Rect rect2 = Rect.Offset(rect1, offsetVector2);
Rect rect3 = Rect.Intersect(this.GetScreenBounds(bounds, targetInterestPoints[]), rect2);
double num5 = rect3 != Rect.Empty ? rect3.Width * rect3.Height : 0.0;
if (num5 - num3 > 0.01)
{
num2 = i;
offsetVector1 = offsetVector2;
num3 = num5;
popupPrimaryAxis = axis;
this.AnimateFromRight = flag1;
this.AnimateFromBottom = flag2;
if (Math.Abs(num5 - num1) < 0.01)
break;
}
}
if (num2 >= && (placement == PlacementMode.Right || placement == PlacementMode.Left))
this.DropOpposite = !this.DropOpposite;
rect1 = new Rect((Size)this._secHelper.GetTransformToDevice().Transform((Point)this._popupRoot.Value.RenderSize));
rect1.Offset(offsetVector1);
Rect screenBounds = this.GetScreenBounds(bounds, targetInterestPoints[]);
Rect rect4 = Rect.Intersect(screenBounds, rect1);
if (Math.Abs(rect4.Width - rect1.Width) > 0.01 || Math.Abs(rect4.Height - rect1.Height) > 0.01)
{
Point point1 = targetInterestPoints[];
Vector vector1 = targetInterestPoints[] - point1;
vector1.Normalize();
if (!this.IsTransparent || double.IsNaN(vector1.Y) || Math.Abs(vector1.Y) < 0.01)
{
if (rect1.Right > screenBounds.Right)
offsetVector1.X = screenBounds.Right - rect1.Width;
else if (rect1.Left < screenBounds.Left)
offsetVector1.X = screenBounds.Left;
}
else if (this.IsTransparent && Math.Abs(vector1.X) < 0.01)
{
if (rect1.Bottom > screenBounds.Bottom)
offsetVector1.Y = screenBounds.Bottom - rect1.Height;
else if (rect1.Top < screenBounds.Top)
offsetVector1.Y = screenBounds.Top;
}
Point point2 = targetInterestPoints[];
Vector vector2 = point1 - point2;
vector2.Normalize();
if (!this.IsTransparent || double.IsNaN(vector2.X) || Math.Abs(vector2.X) < 0.01)
{
if (rect1.Bottom > screenBounds.Bottom)
offsetVector1.Y = screenBounds.Bottom - rect1.Height;
else if (rect1.Top < screenBounds.Top)
offsetVector1.Y = screenBounds.Top;
}
else if (this.IsTransparent && Math.Abs(vector2.Y) < 0.01)
{
if (rect1.Right > screenBounds.Right)
offsetVector1.X = screenBounds.Right - rect1.Width;
else if (rect1.Left < screenBounds.Left)
offsetVector1.X = screenBounds.Left;
}
}
int x = DoubleUtil.DoubleToInt(offsetVector1.X);
int y = DoubleUtil.DoubleToInt(offsetVector1.Y);
if (x == this._positionInfo.X && y == this._positionInfo.Y)
return;
this._positionInfo.X = x;
this._positionInfo.Y = y;
this._secHelper.SetPopupPos(true, x, y, false, , );
}

那么,我们有什么办法调用这个私有方法呢?我相信大家都想,找到popup源码开发者,爆了他Y的!

有一种方法,叫反射,反射可以获取类的任一个字段或者属性。

反射,可以参考:https://www.cnblogs.com/vaevvaev/p/6995639.html

通过反射,我们获取到UpdatePosition方法,并调用执行。

 var mi = typeof(Popup).GetMethod("UpdatePosition", BindingFlags.NonPublic | BindingFlags.Instance);
mi.Invoke(pop, null);

下面是详细的属性更改事件实现:

 private static void OnPopupPlacementTargetChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
Popup pop = d as Popup; //旧值取消LocationChanged监听
if (e.OldValue is DependencyObject previousPlacementTarget)
{
Window window = Window.GetWindow(previousPlacementTarget);
if (window != null)
{
window.LocationChanged -= WindowLocationChanged;
}
} //新值添加LocationChanged监听
if (e.NewValue is DependencyObject newPlacementTarget)
{
Window window = Window.GetWindow(newPlacementTarget);
if (window != null)
{
window.LocationChanged -= WindowLocationChanged;
window.LocationChanged += WindowLocationChanged;
}
}
void WindowLocationChanged(object s1, EventArgs e1)
{
if (pop != null && pop.IsOpen)
{
//通知更新相对位置
var mi = typeof(Popup).GetMethod("UpdatePosition", BindingFlags.NonPublic | BindingFlags.Instance);
mi.Invoke(pop, null);
}
}
}

值得注意的是,原有的绑定目标源要记得取消LocationChanged事件订阅,新的绑定目标源保险起见,也要提前注销再添加事件订阅。

另:通知popup位置更新,也可能通过如下的黑科技:

     //通知更新相对位置
var offset = pop.HorizontalOffset;
pop.HorizontalOffset = offset + ;
pop.HorizontalOffset = offset;

为何改变一下HorizontalOffset就可行呢?因为上面最终并没有改变HorizontalOffset的值。。。

原来。。。好吧,先看源码

     /// <summary>获取或设置目标原点和弹出项对齐之间的水平距离点。</summary>
/// <returns>
/// 目标原点和 popup 对齐点之间的水平距离。
/// 有关目标原点和 popup 对齐点的信息,请参阅 Popup 放置行为。
/// 默认值为 0。
/// </returns>
[Bindable(true)]
[Category("Layout")]
[TypeConverter(typeof (LengthConverter))]
public double HorizontalOffset
{
get
{
return (double) this.GetValue(Popup.HorizontalOffsetProperty);
}
set
{
this.SetValue(Popup.HorizontalOffsetProperty, (object) value);
}
} private static void OnOffsetChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((Popup) d).Reposition();
}

是的,最终调用了Reposition,而Reposition方法中有调用UpdatePosition更新popup位置。

所以以上,更新HorizontalOffset,是更新popup位置的一种捷径。

3. 元素移动/大小变化后,触发更新

当popup的PlaceTarget绑定一个控件或者一个Grid后,FrameworkElement大小变化/位置变化时,popup位置更新(同上)

元素大小变化时:

     else if (newPlacementTarget is FrameworkElement frameworkElement)
{
frameworkElement.SizeChanged -= ElementOnSizeChanged;
frameworkElement.SizeChanged += ElementOnSizeChanged;
}

也可以直接监听LayoutUpdated事件,元素大小/位置变化时,LayoutUpdated都会触发。注意:LayoutUpdated触发有点频繁。

     else if (newPlacementTarget is FrameworkElement frameworkElement)
{
frameworkElement.LayoutUpdated -= ElementOnLayoutUpdated;
frameworkElement.LayoutUpdated += ElementOnLayoutUpdated;
}

4.界面设置绑定目标源

     <Popup x:Name="FirstShowPopup" PlacementTarget="{Binding ElementName=TestButton}" Placement="Custom"
CustomPopupPlacementCallback="{easiUi:Placement Align=RightCenter,OutOfScreenEnabled=True}" PopupAnimation="Fade"
AllowsTransparency="True" StaysOpen="True" HorizontalOffset="-16" VerticalOffset="4"
helper:PopupHelper.LocationUpdatedOnTarget="{Binding ElementName=TestButton}"
helper:PopupHelper.TopmostInCurrentWindow="True">
</Popup>

最新文章

  1. C# PPT Operator
  2. pip高级使用技巧以及搭建自己的pypi服务器
  3. SQL 大数据查询如何进行优化?
  4. Map/Reduce 工作机制分析 --- 数据的流向分析
  5. C++之路进阶——bzoj1823(满汉全席)
  6. [WCF]IIS部署到新系统
  7. 火狐flash插件
  8. Android无法导入下载好的项目(和Eclipse中已经存在的项目命名一样导致冲突)解决办法
  9. FineUI上传控件
  10. 怎样用OleDbDataAdapter来对数据库进行操作?
  11. SQL Server中存储过程比直接运行SQL语句慢的原因
  12. STM32的优先级NVIC_PriorityGroupConfig
  13. Win10下, TortoiseGit安装及配合Gitee使用完整版
  14. 用JDBC把Excel中的数据导入到Mysql数据库中
  15. &quot;Last_IO_Error: Fatal error: The slave I/O thread stops because master and slave have equal MySQL server UUIDs
  16. tcp协议下粘包问题的产生及解决方案
  17. 学习Junit资料
  18. [XPath] XPath 与 lxml (四)XPath 运算符
  19. AngularJS中ng-class使用方法
  20. 可视化库-Matplotlib-饼图与布局(第四天)

热门文章

  1. Flask项目之手机端租房网站的实战开发(六)
  2. Web应用开发(Servlet+html+Mysql)入门小示例
  3. GO语言学习(十六)Go 语言结构体
  4. Altium Designer导入pcb原件之后都是绿的
  5. springMVC easyUI filebox 单个文件上传
  6. amazeui学习笔记--js插件(UI增强4)--下拉组件Dropdown
  7. IOS基础:深入理解Objective-c中@class 和#import的区别
  8. Unity插件之NGUI学习(5)—— 创建Label图文混排及文字点击
  9. thinkphp3.1课程 1-1 为什么thinkphp在开发好后需要关掉开发模式
  10. 洛谷 P3871 中位数