C#/WPF: Place Popup Control in Center of Screen?

一曲冷凌霜 提交于 2019-12-03 23:21:25

问题


Does anyone know how I can place a Popup Control in the Center of the screen?

Thanks!


回答1:


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"
>



回答2:


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;



回答3:


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>



回答4:


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.



来源:https://stackoverflow.com/questions/1762113/c-wpf-place-popup-control-in-center-of-screen

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!