Reputation: 6397
Does anyone know how I can place a Popup Control in the Center of the screen?
Thanks!
Upvotes: 26
Views: 39025
Reputation: 11
From the code behind, you can write this. It will alwasy center of the parent whenever your parent is:
popup.Left = (parent.Left + (parent.Width / 2)) - (popup.Width / 2);
popup.Top = (parent.Top + (parent.Height / 2)) - (popup.Height / 2);
Upvotes: 0
Reputation: 656
You can use Placement="Center" and find ancestor Window using RelativeSource and set "PlacementTarget" property as property like this:
<Popup
Placement="Center"
PlacementTarget="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}}"
PopupAnimation="Slide">
<ContentControl Content="{Binding Yourcontent}"/>
</Popup>
And to keep stupid comments refrained: I know this centers the popup in the middle of the parent window (not neccessarily middle of the screen [if the parent window is not centered on the screen, what really is not regular case]) but this shall statisfy in most of the cases.
Upvotes: 1
Reputation: 2420
Use the Placement and PlacementTarget properties to position it relative to whatever panel is at the root of the window. So if I have a Grid
, StackPanel
, etc. that contains all the other "stuff" in the window called MainPanel
, I do something like:
<Popup
PlacementTarget="{Binding ElementName=MainPanel}"
Placement="Center"
>
Upvotes: 30
Reputation: 3329
None of these answers worked for me in part because I don't have the size of the Popup. I ended up doing this in code behind as follows:
var popup = new Popup
{
Child = new YourUIControlHere(),
Placement = PlacementMode.Center,
PlacementRectangle = new Rect(new Size(
SystemParameters.FullPrimaryScreenWidth,
SystemParameters.FullPrimaryScreenHeight))
};
This could easily be extended to XAML by adding a binding for the screen size.
An obvious enhancement is to use the current screen for multi-monitor support. Getting the current window dimensions is considerably more work however.
Upvotes: 3
Reputation: 10534
Use Grid as container and Alignment will work fine for you:
<Popup IsOpen="True">
<Grid Name="canvasMain">
<StackPanel VerticalAlignment="Center" HorizontalAlignment="Center">
...
</StackPanel>
</Grid>
</Popup>
Upvotes: 2
Reputation: 15678
First, you can use the static properties FullPrimaryScreenHeight
, FullPrimaryScreenWidth
of the System.Windows.SystemParameters
class to get the height and width of the screen. Then, you can set the Top
and Left
properties of your Popup Control using the width and height before showing it.
Something like.
double primScreenHeight = System.Windows.SystemParameters.FullPrimaryScreenHeight;
double primScreenWidth = System.Windows.SystemParameters.FullPrimaryScreenWidth;
_yourControl.Top = (primScreenHeight - _yourControl.Height) / 2;
_yourControl.Left = (primScreenWidth - _yourControl.Width) / 2;
Upvotes: 3