WPF自定义Popup位置

popup的位置是通过属性Placement 来控制的,如果想自己定义popup位置,那么需要将Placement 属性设置为Custom。

当 Placement 属性设置为时 Custom ,将 Popup 调用已定义的委托实例 CustomPopupPlacementCallback 。 此委托返回一组可能的点,这些点相对于目标区域的左上角和左上角 Popup 。 Popup放置在提供最佳可见性的点上。

下面是用法:

xaml代码

<Popup Name="popup1"  
        PlacementTarget ="{Binding ElementName=myButton}" 
        Placement="Custom">
  <TextBlock Height="60" Width="200" 
             Background="LightGray"
             TextWrapping="Wrap">Popup positioned by using
  CustomPopupPlacement callback delegate</TextBlock>
</Popup>

C#代码

popup1.CustomPopupPlacementCallback = new CustomPopupPlacementCallback(placePopup);

public CustomPopupPlacement[] placePopup(Size popupSize, Size targetSize, Point offset) { CustomPopupPlacement placement1 = new CustomPopupPlacement(new Point(-50, 100), PopupPrimaryAxis.Vertical); CustomPopupPlacement placement2 = new CustomPopupPlacement(new Point(10, 20), PopupPrimaryAxis.Horizontal); CustomPopupPlacement[] ttplaces = new CustomPopupPlacement[] { placement1, placement2 }; return ttplaces; }

来看一下placePopup方法的参数offset

offset是popup位置的坐标,默认为(0,0),下面的纵向和横向偏移量是根据此点坐标来说的,如果要指定popup的起始坐标,应设置popup的VerticalOffset和HorizontalOffset

比如说要设置为鼠标点的位置为默认起始点,则应该设置:

Point mousePoint = Mouse.GetPosition(canvas);//比如canvas为所在画布

popup.VerticalOffset = mousePoint.Y;
popup.HorizontalOffset = mousePoint.X;

  

原文地址:https://www.cnblogs.com/cuigzh/p/14271471.html