I have a popup that is attached right to a custom window:
<Popup x:Name="myPopup"
Width="250"
Height="250"
HorizontalOffset="50"
Placement="Right"
PlacementTarget="{Binding ElementName=MyWindow}">
</Popup>
In code-behind, on the window LocationChanged event, I update the position of the popup:
myCustomWindow.LocationChanged += (object sender, EventArgs args) =>
{
myPopup.HorizontalOffset +=1;
myPopup.HorizontalOffset -= 1;
};
My problem is that if the popup encounters the right edge of the screen, it will automatically be moved to the left side of the window, but in this case the HorizontalOffset should be -50.
How can I set the HorizontalOffset dynamically?
Have a look at https://learn.microsoft.com/en-us/dotnet/desktop/wpf/controls/how-to-specify-a-custom-popup-position?view=netframeworkdesktop-4.8
In my opinion you should employ CustomPopupPlacementCallback
.
In order to do so:
change the placement of your Popup to
Placement="Custom"
Define the following method:
public CustomPopupPlacement[] placePopup(Size popupSize, Size targetSize, Point offset)
{
return new CustomPopupPlacement[]
{
new CustomPopupPlacement(new Point(targetSize.Width, 0), PopupPrimaryAxis.Horizontal),
new CustomPopupPlacement(new Point(-popupSize.Width - 2 * offset.X, 0), PopupPrimaryAxis.Horizontal)
};
}
And finally, in the place where you open your popup (e.g. main window loaded event callback), assign the custom callback to the popup:
myPopup.CustomPopupPlacementCallback = new CustomPopupPlacementCallback(placePopup);
In short, what it does is that it places the popup according to the zeroth element of the CustomPopupPlacement
array unless a collision with the edge is detected, then the placement happens according to the first element of the array.