Get the height/width of Window WPF Get the height/width of Window WPF wpf wpf

Get the height/width of Window WPF


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.

When WindowState == Normal You can do this one from Width / Height after IntializeComponent().

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

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


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

this.SizeChanged += OnWindowSizeChanged;

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

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.

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.

Here is the OnWindowSizeChanged event handler:

    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;    }


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