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;