原文: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>

Popup 解决位置不随窗口/元素FrameworkElement 移动更新的问题的更多相关文章

  1. 解决 Popup 位置不随窗口移动更新的问题

    Popup弹出后,因业务需求设置了StaysOpen=true后,移动窗口位置或者改变窗口大小,Popup的位置不会更新. 如何更新位置? 获取当前Popup的Target绑定UserControl所 ...

  2. svn更新路径,解决办法详细步骤,eclipse里面的更新方法,svn废弃位置,Windows环境,svn服务器地址换了,如何更新本地工作目录

    svn更新路径,解决办法详细步骤,eclipse里面的更新方法,svn废弃位置,Windows环境,svn服务器地址换了,如何更新本地工作目录 Windows下,svn服务器IP本来是内网一台服务器上 ...

  3. LinearLayout的gravity属性以及其子元素的layout_gravity何时有效;RelativeLayout如何调整其子元素位置只能用子元素中的属性来控制,用RelativeLayout中的gravity无法控制!!!

    LinearLayout的gravity属性以及其子元素的layout_gravity何时有效:RelativeLayout如何调整其子元素位置只能用子元素中的属性来控制,用RelativeLayou ...

  4. Notepad++源代码阅读——窗口元素组织与布局

    1.1 前言 这两天在看notepad++ 1.0版本的源代码.看了许久终于把程序的窗口之间的关系搞清楚了现在把其组织的要点写于此,希望对大家有所帮助. 1.2 窗口元素之间的关系 Notepad++ ...

  5. Popup 解决置顶显示问题

    原文:Popup 解决置顶显示问题 前言 Popup显示时会置顶显示.尤其是 Popup设置了StayOpen=true时,会一直置顶显示,问题更明显. 置顶显示问题现象: 解决方案 怎么解决问题? ...

  6. [ucgui] 对话框5——鼠标位置和移动窗口

    >_<" 这节主要是获取鼠标的位置和把窗口设置为可以移动.其中设置窗口可以移动用FRAMEWIN_SetMoveable(hFrameWin, 1)就行了.而获得鼠标位置则是利用 ...

  7. jeecg项目子窗口获得父窗口元素id

    jeecg项目子窗口获得父窗口元素id, var parentWin = frameElement.api.opener;alert($(parentWin.document).find(" ...

  8. 能用padding,margin解决的不要使用伪元素,能用背景解决的也不要用伪元素

    能用padding,margin解决的不要使用伪元素,能用背景解决的也不要用伪元素

  9. 一句white-space:nowrap解决IE6,IE7下浮动元素不自动换行

    一句white-space:nowrap解决IE6,IE7下浮动元素不自动换行

随机推荐

  1. Vue 自定义全局消息框组件

    消息弹框组件,默认3秒后自动关闭,可设置info/success/warning/error类型 效果图: 文件目录: Message.vue <template> <transit ...

  2. document.write的注意点

    如果给button点击事件添加document.write会消除页面所有元素,包括button按钮 <!DOCTYPE html> <html> <head> &l ...

  3. C#正则表达式匹配HTML中的图片路径,图片地址

    C#正则表达式匹配HTML中的图片路径,图片地址 最近的项目中有个关于网页取图的功能需要我自己开发,那就是用正则表达式来匹配图片标签.       一般来说一个 HTML 文档有很多标签,比如“< ...

  4. html 代码

    1.结构性定义 文件类型 <HTML></HTML> (放在档案的开头与结尾) 文件主题 <TITLE></TITLE> (必须放在「文头」区块内) 文 ...

  5. 关于VUE的安装和一些简单属性

    安装vue 安装前初始化package.json 主要用来描述自己的项目,记录安装过得文件有哪些,在当前文件夹下生产json 安装vue --save(-S)代表项目依赖 --save-dev(-D) ...

  6. OFFICE2013 打开两个word文档卡死的解决办法

    这几天Office打开一个word好好的,两个就直接卡死了,百度了一下: 原文地址: http://hi.baidu.com/pjhero/item/ca326e3dcfebebb9623aff6e ...

  7. python3 打印九九乘法表

    打印九九乘法表 # !/usr/bin/env python # -*- coding:utf-8 -*- # Author:Hiuhung Wan for i in range(1, 10): fo ...

  8. js进阶 11-22/23 js如何实现选项卡

    js进阶 11-22/23 js如何实现选项卡 一.总结 一句话总结:通过索引把选项卡头的li标签和选项卡内容的div标签联系在一起,通过控制div标签的display属性可以实现选项卡的选项切换. ...

  9. 【心情】Priority_queue容器的用法

    所给的代码最顶端是最小的元素 要改为最顶端是最大的则只需把 friend bool operator<(Node a, Node b) { return a.val > b.val; } ...

  10. 【42.59%】【codeforces 602A】Two Bases

    time limit per test1 second memory limit per test256 megabytes inputstandard input outputstandard ou ...