简体   繁体   English

获取 Window WPF 的高度/宽度

[英]Get the height/width of Window WPF

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.该应用程序不会全屏运行。

You can get the width and height that the window was meant to be in the constructor after InitializeComponent has been run, they won't return NaN then, the actual height and width will have to wait until the window has been displayed. 在运行InitializeComponent之后,您可以获得窗口在构造函数中的宽度和高度,然后它们将不返回NaN ,实际的高度和宽度必须等到窗口显示。

When WindowState == Normal You can do this one from Width / Height after IntializeComponent() . WindowState == Normal你可以在IntializeComponent()之后从Width / Height执行此操作。

When WindowState == Maximized You could get the screen resolution for this one with WindowState == Maximized你可以得到这个的屏幕分辨率

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

You have to try to get the ActualWidth/ActualHeight values once the window is Loaded in the UI. 在UI中加载窗口后,您必须尝试获取ActualWidth/ActualHeight值。 Doing it in Window_Loaded works well. 在Window_Loaded中执行它很有效。

1.) Subscribe to the window re size event in the code behind: 1.)在后面的代码中订阅窗口重新调整大小事件:

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: 这是代码,更具体的例子:

NOTE I have a private instance integer called 'resizeMode' that is set to 0 in the constructor the Window code behind. 注意我有一个名为'resizeMode'的私有实例整数,在后面的Window代码的构造函数中设置为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;
    }

XAML XAML

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

CS MainWindow() after InitializeComponent(); 在InitializeComponent()之后的CS MainWindow();

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

WPF does the creation of controls and windows in a deferred manner. WPF以延迟的方式创建控件和窗口。 So until the window is displayed for the first time, it might not have gone through layouting yet, thus no ActualWidth / ActualHeight . 因此,在第一次显示窗口之前,它可能尚未进行布局,因此没有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() . 您还可以通过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. 除非您正在编写布局面板。

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. 您可以在触发Loaded事件时检查ActualHeigh或ActualWidth,但在创建Windows控件之前不要尝试验证它。 Forget the idea to control that in the constructor. 忘记在构造函数中控制它的想法。

In my oppinion, the best place to control this kind of things is The SizeChanged event 在我看来,控制这类事情的最佳地方是The SizeChanged事件

嗨,您可以使用 WPF 获取当前屏幕的高度

System.Windows.SystemParameters.PrimaryScreenHeight

I just add a variable name to my window and then get the width or height of the window i want from its width or height property respectifly.我只是在我的窗口中添加一个变量名,然后分别从它的宽度或高度属性中获取我想要的窗口的宽度或高度。

XAML: XAML:

<Window x:Name="exampleName"
   ...
</Window>

C#: C#:

exampleName.Height;

or:或者:

exampleName.Width;

My solution in case of MVVM...我在 MVVM 的情况下的解决方案......

I have a ViewModelBase , which is the base class for all ViewModel of the app.我有一个ViewModelBase ,它是应用程序所有 ViewModel 的基础 class 。

1.) I created in the ViewModelBase a virtual method, which could be overriten in the child ViewModels. 1.) 我在ViewModelBase中创建了一个虚拟方法,它可以在子 ViewModel 中被覆盖。

public virtual void OnWindowSizeChanged(object sender, SizeChangedEventArgs e) {}

2.) The ctr of the MainWindow: Window class 2.) 主窗口的 ctr MainWindow: Window class

public MainWindow(object dataContext)
{
    InitializeComponent();

    if (dataContext is ViewModelBase)
    {
        this.SizeChanged += ((ViewModelBase)dataContext).OnWindowSizeChanged;
        DataContext = dataContext;
    }
}

3.) Eg. 3.) 例如。 in the MainViewModel , which is extends the ViewModelBaseMainViewModel中,它扩展了ViewModelBase

public override void OnWindowSizeChanged(object sender, SizeChangedEventArgs e)
{
    Console.WriteLine(e.NewSize.Height);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM