首页 技术 正文
技术 2022年11月13日
0 收藏 314 点赞 2,747 浏览 8603 个字

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位置的!

解决 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>
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,494
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,907
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,740
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,495
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,133
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,297