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);
var element = previousPlacementTarget as FrameworkElement;
if (window != null)
{
CancelEventsListeningInWindow(window);
}
if (element != null)
{
element.SizeChanged -= ElementSizeChanged;
element.LayoutUpdated -= ElementLayoutUpdated;
}
} //新值添加LocationChanged监听
if (e.NewValue is DependencyObject newPlacementTarget)
{
Window window = Window.GetWindow(newPlacementTarget);
var element = newPlacementTarget as FrameworkElement;
//窗口已加载
if (window != null)
{
RegisterEventsInWindow(window);
}
//窗口未加载,则等待控件初始化后,再获取窗口
else if (element != null)
{
element.Loaded -= ElementLoaded;
element.Loaded += ElementLoaded;
}
//元素大小变换时,变更Popup位置
if (element != null)
{
element.SizeChanged -= ElementSizeChanged;
element.SizeChanged += ElementSizeChanged;
element.LayoutUpdated -= ElementLayoutUpdated;
element.LayoutUpdated += ElementLayoutUpdated;
}
void ElementLoaded(object sender, RoutedEventArgs e3)
{
element.Loaded -= ElementLoaded;
window = Window.GetWindow(newPlacementTarget);
if (window != null)
{
RegisterEventsInWindow(window);
}
}
}
void RegisterEventsInWindow(Window window)
{
window.LocationChanged -= WindowLocationChanged;
window.LocationChanged += WindowLocationChanged;
window.SizeChanged -= WindowSizeChanged;
window.SizeChanged += WindowSizeChanged;
}
void CancelEventsListeningInWindow(Window window)
{
window.LocationChanged -= WindowLocationChanged;
window.SizeChanged -= WindowSizeChanged;
}
void WindowLocationChanged(object s1, EventArgs e1)
{
UpdatePopupLocation();
}
void WindowSizeChanged(object sender, SizeChangedEventArgs e2)
{
UpdatePopupLocation();
}
void ElementSizeChanged(object sender, SizeChangedEventArgs e3)
{
UpdatePopupLocation();
}
void ElementLayoutUpdated(object sender, EventArgs e4)
{
UpdatePopupLocation();
}
void UpdatePopupLocation()
{
if (pop != null && pop.IsOpen)
{
//通知更新相对位置
var method = typeof(Popup).GetMethod("UpdatePosition", BindingFlags.NonPublic | BindingFlags.Instance);
method?.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 位置不随窗口移动更新的问题的更多相关文章

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

    原文:Popup 解决位置不随窗口/元素FrameworkElement 移动更新的问题 Popup弹出后,因业务需求设置了StaysOpen=true后,移动窗口位置或者改变窗口大小,Popup的位 ...

  2. 解决Popup StayOpen=true时,永远置顶的问题

    Popup设置了StayOpen=true时,会置顶显示. 如弹出了Popup后,打开QQ窗口,Popup显示在QQ聊天界面之上. 怎么解决问题? 获取绑定UserControl所在的窗口,窗口层级变 ...

  3. Vivado_MicroBlaze_问题及解决方法_汇总(不定时更新)

    Vivado_MicroBlaze_问题及解决方法_汇总(不定时更新) 标签: Vivado 2015-07-03 14:35 4453人阅读 评论(0) 收藏 举报  分类: 硬件(14)  版权声 ...

  4. 解决popup不随着window一起移动的问题

    原文:解决popup不随着window一起移动的问题 当我们设置Popup的StayOpen="True"时,会发现移动窗体或者改变窗体的Size的时候,Popup并不会跟随着一起 ...

  5. 解决 WPF 嵌套的子窗口在改变窗口大小的时候闪烁的问题

    原文:解决 WPF 嵌套的子窗口在改变窗口大小的时候闪烁的问题 因为 Win32 的窗口句柄是可以跨进程传递的,所以可以用来实现跨进程 UI.不过,本文不会谈论跨进程 UI 的具体实现,只会提及其实现 ...

  6. IOS8解决获取位置坐标信息出错(Error Domain=kCLErrorDomain Code=0)(转)

    标题:IOS8解决获取位置坐标信息出错(Error Domain=kCLErrorDomain Code=0) 前几天解决了在ios8上无法使用地址位置服务的问题,最近在模拟器上调试发现获取位置坐标信 ...

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

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

  8. Vue解决同一页面跳转页面不更新

    问题分析:路由之间的切换,其实就是组件之间的切换,不是真正的页面切换.这也会导致一个问题,就是引用相同组件的时候,会导致该组件无法更新. 方案一:使用 watch 进行监听 watch: { /* = ...

  9. [转帖]升级 Ubuntu,解决登录时提示有软件包可以更新的问题

    升级 Ubuntu,解决登录时提示有软件包可以更新的问题 2017年12月05日 11:58:17 阅读数:2953更多 个人分类: ubuntu Connecting to ... Connecti ...

随机推荐

  1. 新概念英语(1-133)Sensational news!

    Lesson 133 Sensational news! 爆炸性新闻! Listen to the tape then answer this question. What reason did Ka ...

  2. MicrosoftWebInfrastructure 之坑

    从svn下载下来的项目,还原提示缺少MicrosoftWebInfrastructure   包 网上大多数解决方法  PM> Install-Package Microsoft.Web.Inf ...

  3. python之路——初识函数

    阅读目录 为什么要用函数 函数的定义与调用 函数的返回值 函数的参数 本章小结 返回顶部 为什么要用函数 现在python届发生了一个大事件,len方法突然不能直接用了... 然后现在有一个需求,让你 ...

  4. tcpdump记录

    tcpdump -i eth0 -nn -A -X 'host 192.168.20.82 and port 9080' -i:interface 监听的网卡. -nn:表示以ip和port的方式显示 ...

  5. Vue框架

    Vue框架 环境: windows python3.6.2 Vue的cdn: <script src="https://cdn.jsdelivr.net/npm/vue"&g ...

  6. pythonllk

    字符编码 数据类型 函数  装饰器  内置函数 迭代器 生成器 异常 反射 模块 类 对象 类的进阶 socket 进程线程 httphtmlcssJavaScriptjquery MysqlMysq ...

  7. uva 10917 Walk Through The Forest

    题意: 一个人从公司回家,他可以从A走到B如果从存在从B出发到家的一条路径的长度小于任何一条从A出发到家的路径的长度. 问这样的路径有多少条. 思路: 题意并不好理解,存在从B出发到家的一条路径的长度 ...

  8. CSS 选择器简介

    前言:这是笔者学习之后自己的理解与整理.如果有错误或者疑问的地方,请大家指正,我会持续更新! 选择器权重 如果以4位数表示选择符权重,那么: 元素选择器的权重是1: id 选择器的权重为100: cl ...

  9. ORA-09925: Unable to create audit trail file带来的sqlplus / as sysdba无法连接

    SQL> show parameter pfile; /picclife/app/oracle/product/11.2.0/dbhome_1/dbs/spfilehukou.ora SQL&g ...

  10. Docker下ETCD集群搭建

    搭建集群之前首先准备两台安装了CentOS 7的主机,并在其上安装好Docker. Master 10.100.97.46 Node 10.100.97.64 ETCD集群搭建有三种方式,分别是Sta ...