如何:指定自定义弹出窗口位置

此示例演示如何在当Placement属性设置为Custom时,为Popup控件指定自定义位置。

示例:

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

以下示例演示如何通过将Placement属性设置为Custom来定义Popup的位置。 它还演示如何创建和指派 CustomPopupPlacementCallback 委托以定位该 Popup。 回调委托函数返回两个CustomPopupPlacement对象。 如果Popup在第一个位置被屏幕边缘隐藏,则Popup位于第二个位置。

 <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>
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;
}
Public Function placePopup(ByVal popupSize As Size, ByVal targetSize As Size, ByVal offset As Point) As CustomPopupPlacement()
    Dim placement1 As New CustomPopupPlacement(New Point(-50, 100), PopupPrimaryAxis.Vertical)

    Dim placement2 As New CustomPopupPlacement(New Point(10, 20), PopupPrimaryAxis.Horizontal)

    Dim ttplaces() As CustomPopupPlacement = { placement1, placement2 }
    Return ttplaces
End Function
popup1.CustomPopupPlacementCallback =
    new CustomPopupPlacementCallback(placePopup);
popup1.CustomPopupPlacementCallback = New CustomPopupPlacementCallback(AddressOf placePopup)

有关完整示例,请参阅 弹出窗口放置示例

另请参阅