C#/WPF:将弹出控件放在屏幕中央?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1762113/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C#/WPF: Place Popup Control in Center of Screen?
提问by Joseph jun. Melettukunnel
Does anyone know how I can place a Popup Control in the Center of the screen?
有谁知道如何在屏幕中央放置一个弹出控件?
Thanks!
谢谢!
采纳答案by Tim Ridgely
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:
使用 Placement 和 PlacementTarget 属性将其相对于窗口根部的任何面板定位。所以,如果我有一个Grid
,StackPanel
等包含在所谓的窗口中的所有其他的“东西” MainPanel
,我这样做:
<Popup
PlacementTarget="{Binding ElementName=MainPanel}"
Placement="Center"
>
回答by tranmq
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.
首先,你可以使用静态属性FullPrimaryScreenHeight
,FullPrimaryScreenWidth
该的System.Windows.SystemParameters
类来获取屏幕的高度和宽度。然后,您可以在显示之前使用宽度和高度设置弹出控件的Top
和Left
属性。
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;
回答by Vitaliy Ulantikov
Use Grid as container and Alignment will work fine for you:
使用 Grid 作为容器,Alignment 可以很好地为您工作:
<Popup IsOpen="True">
<Grid Name="canvasMain">
<StackPanel VerticalAlignment="Center" HorizontalAlignment="Center">
...
</StackPanel>
</Grid>
</Popup>
回答by Mike Ward
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.
通过为屏幕大小添加绑定,这可以轻松扩展到 XAML。
An obvious enhancement is to use the current screen for multi-monitor support. Getting the current window dimensions is considerably more work however.
一个明显的增强是使用当前屏幕来支持多显示器。然而,获取当前窗口尺寸的工作要多得多。