Get the height/width of Window WPF
c#, height, width, wpf, xaml
Solution
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;
}
Problem
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 Can anyone tell me a way of getting it ? These 2 methods don't work ``` //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.