C# 获取Window WPF的高度/宽度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11013316/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 16:06:47  来源:igfitidea点击:

Get the height/width of Window WPF

c#wpfxamlheightwidth

提问by Welsh King

I have the following code

我有以下代码

<Window x:Class="Netspot.DigitalSignage.Client.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" WindowStyle="SingleBorderWindow" 
        WindowStartupLocation="CenterScreen"
        WindowState="Normal" Closing="Window_Closing">

Any attempt to get the height / width return NaN or 0.0

任何获取高度/宽度的尝试都返回 NaN 或 0.0

Can anyone tell me a way of getting it ?

谁能告诉我一种获得它的方法吗?

These 2 methods don't work

这2个方法不起作用

//Method1
var h = ((System.Windows.Controls.Panel)Application.Current.MainWindow.Content).ActualHeight;
var w = ((System.Windows.Controls.Panel)Application.Current.MainWindow.Content).ActualWidth;

//Method2
double dWidth = -1;
double dHeight = -1;
FrameworkElement pnlClient = this.Content as FrameworkElement;
if (pnlClient != null)
{
     dWidth = pnlClient.ActualWidth;
     dHeight = pnlClient.ActualWidth;
}

The application will not be running full screen.

该应用程序不会全屏运行。

回答by dowhilefor

WPF does the creation of controls and windows in a deferred manner. So until the window is displayed for the first time, it might not have gone through layouting yet, thus no ActualWidth/ActualHeight. You can wait until the window is loaded and get the properties then, or yet better bind these properties to a target where you need them. You could also force the layouting via UpdateLayout().

WPF 以延迟方式创建控件和窗口。所以在第一次显示窗口之前,它可能还没有经过布局,因此没有ActualWidth/ ActualHeight。您可以等到窗口加载后获取属性,或者更好地将这些属性绑定到您需要它们的目标。您也可以通过UpdateLayout().

Just want to add: try to minimize the amount of size dependant logic, it is almost always possible to avoid it. Unless you are writing a layout panel of course.

只想补充一点:尽量减少依赖于大小的逻辑的数量,几乎总是可以避免的。当然,除非您正在编写布局面板。

回答by Andy

You can get the width and height that the window was meant to be in the constructor after InitializeComponenthas been run, they won't return NaNthen, the actual height and width will have to wait until the window has been displayed.

您可以InitializeComponent在运行后获得窗口在构造函数中的宽度和高度,NaN然后它们不会返回,实际的高度和宽度必须等到窗口显示出来。

When WindowState == NormalYou can do this one from Width / Heightafter IntializeComponent().

何时WindowState == Normal您可以从Width / Height之后执行此操作IntializeComponent()

When WindowState == MaximizedYou could get the screen resolution for this one with

WindowState == Maximized你可以得到这个的屏幕分辨率时

System.Windows.SystemParameters.PrimaryScreenHeight;
System.Windows.SystemParameters.PrimaryScreenWidth;

回答by David Bekham

You have to try to get the ActualWidth/ActualHeightvalues once the window is Loaded in the UI. Doing it in Window_Loaded works well.

ActualWidth/ActualHeight在 UI 中加载窗口后,您必须尝试获取这些值。在 Window_Loaded 中这样做效果很好。

回答by kformeck

1.) Subscribe to the window re size event in the code behind:

1.) 在后面的代码中订阅window re size事件:

this.SizeChanged += OnWindowSizeChanged;

2.) Use the SizeChangedEventArgs object 'e' to get the sizes you need:

2.) 使用 SizeChangedEventArgs 对象 'e' 来获取您需要的大小:

protected void OnWindowSizeChanged(object sender, SizeChangedEventArgs e)
{
    double newWindowHeight = e.NewSize.Height;
    double newWindowWidth = e.NewSize.Width;
    double prevWindowHeight = e.PreviousSize.Height;
    double prevWindowWidth = e.PreviousSize.Width;
}

Keep in mind this is very general case, you MAY (you may not either) have to do some checking to make sure you have size values of 0.

请记住,这是非常普遍的情况,您可能(也可能不会)必须进行一些检查以确保大小值为 0。

I used this to resize a list box dynamically as the main window changes. Essentially all I wanted was this control's height to change the same amount the window's height changes so its parent 'panel' looks consistent throughout any window changes.

我用它来随着主窗口的变化动态调整列表框的大小。基本上我想要的只是这个控件的高度改变窗口高度的变化量,这样它的父“面板”在任何窗口变化中看起来都是一致的。

Here is the code for that, more specific example:

这是代码,更具体的例子:

NOTEI have a private instance integer called 'resizeMode' that is set to 0 in the constructor the Window code behind.

注意我有一个名为“resizeMode”的私有实例整数,它在窗口代码后面的构造函数中设置为 0。

Here is the OnWindowSizeChanged event handler:

这是 OnWindowSizeChanged 事件处理程序:

    protected void OnWindowSizeChanged (object sender, SizeChangedEventArgs e)
    {
        if (e.PreviousSize.Height != 0)
        {
            if (e.HeightChanged)
            {
                double heightChange = e.NewSize.Height - e.PreviousSize.Height;
                if (lbxUninspectedPrints.Height + heightChange > 0)
                {
                    lbxUninspectedPrints.Height = lbxUninspectedPrints.Height + heightChange;
                }
            }
        }
        prevHeight = e.PreviousSize.Height;
    }

回答by Vilintritenmert

XAML

XAML

<Grid x:Name="Grid1">
      <Image x:Name="Back_Image" HorizontalAlignment="Left" VerticalAlignment="Top"/>
</Grid>

CSMainWindow() after InitializeComponent();

在 InitializeComponent() 之后的CSMainWindow();

    Back_Image.Width = Grid1.Width;
    Back_Image.Height = Grid1.Height;

回答by Edheo

Notice that when you use controls with 100% of with, they have a NaN size till they are being represented

请注意,当您使用 100% with 的控件时,它们的大小为 NaN,直到它们被表示

You can check the ActualHeigh or ActualWidth just when the Loaded event is fired, but never try to verify it before the windows controls are created. Forget the idea to control that in the constructor.

您可以在 Loaded 事件触发时检查 ActualHeigh 或 ActualWidth,但在创建 windows 控件之前不要尝试验证它。忘记在构造函数中控制它的想法。

In my oppinion, the best place to control this kind of things is The SizeChanged event

在我看来,控制这种事情的最好地方是 SizeChanged 事件