我有以下行為可以從這里用滑鼠拖動彈出視窗
wpf 中的可拖動彈出控制元件
public class MouseDragPopupBehavior : Behavior<Popup>
{
private bool mouseDown;
private Point oldMousePosition;
protected override void OnAttached()
{
AssociatedObject.MouseLeftButtonDown = (s, e) =>
{
mouseDown = true;
oldMousePosition = AssociatedObject.PointToScreen(e.GetPosition(AssociatedObject));
AssociatedObject.Child.CaptureMouse();
};
AssociatedObject.MouseMove = (s, e) =>
{
if (!mouseDown) return;
var newMousePosition = AssociatedObject.PointToScreen(e.GetPosition(AssociatedObject));
var offset = newMousePosition - oldMousePosition;
oldMousePosition = newMousePosition;
AssociatedObject.HorizontalOffset = offset.X;
AssociatedObject.VerticalOffset = offset.Y;
};
AssociatedObject.MouseLeftButtonUp = (s, e) =>
{
mouseDown = false;
AssociatedObject.Child.ReleaseMouseCapture();
};
}
}
這是有效的,但是當我使用自定義放置將彈出視窗定位在我的視窗右下角時,移動不是 1:1。
public class MyPopup : Popup
{
...
CustomPopupPlacementCallback = (Size popupSize, Size targetSize, Point offset) =>
{
offset.X = targetSize.Width - popupSize.Width - 50;
offset.Y = targetSize.Height - popupSize.Height - 100;
return new[] { new CustomPopupPlacement(offset, PopupPrimaryAxis.Horizontal) };
};
}
彈出視窗比滑鼠移動得更多,最終游標不再位于彈出視窗的上方。
如何調整此代碼,以便彈出視窗與游標完全一致?
uj5u.com熱心網友回復:
我相信這兩者不能很好地協同作業,主要是因為有一些關于如何選擇放置位置的重要邏輯CustomPopupPlacementCallback以防萬一。
您觀察到的行為是因為您在這里增加了偏移量:
offset.X = targetSize.Width - popupSize.Width - 50;
offset.Y = targetSize.Height - popupSize.Height - 100;
這偏移HorizontalOffset和VerticalOffset你拖行為設定。但是您期望從該自定義回呼回傳的是相對位置,因此您無需為其添加偏移量。例如,將修復它:
var x = targetSize.Width - popupSize.Width - 50;
var y = targetSize.Height - popupSize.Height - 100;
return new[] { new CustomPopupPlacement(new Point(x, y), PopupPrimaryAxis.Vertical) };
但是,無論如何,您都會在靠近螢屏邊緣的多顯示幕設定中遇到問題(與您現在遇到的問題不同)。執行拖動時也會多次呼叫此回呼,從而影響性能。
我建議只在打開時放置一次彈出視窗。將 PlacementRelative設定PlacementTarget為并根據需要進行設定(可能您已經這樣做了),然后只需計算打開時的偏移量。你可以在拖動行為本身中做到這一點(當然,它不再只是拖動行為,但我不會在這里打擾干凈的編碼實踐):
AssociatedObject.Opened = (o, e) => {
var popupRoot = (FrameworkElement)AssociatedObject.Child;
var target = (FrameworkElement)AssociatedObject.PlacementTarget; // you can use "constraint" from other question here
AssociatedObject.HorizontalOffset = target.ActualWidth - popupRoot.ActualWidth - 50;
AssociatedObject.VerticalOffset = target.ActualHeight - popupRoot.ActualHeight - 100;
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/315355.html
下一篇:Microsoft.Extensions.Caching和System.Runtime.Caching有什么區別?
