All the suggested solutions are based on the idea to use the size of Windows.Content
to know what is the actual size available within the window, like this:
var h = ((Panel)Application.Current.MainWindow.Content).ActualHeight;
This of course only works if Window.Content
is not null. Which is a problem if you want to set Window.Content
from your code and you already then need to know exactly how much space is available.
The other problem is that the above code only provides the available space once a first layout cycle has completed (i.e. in the Window_Loaded
event). But what do you do if you need to know the available space during the first layout cycle, for example because you draw to the window during Windows.OnRender()
?
The first control in the visual tree of any Window
is always a Border
, even if Window.Content
is null. Interestingly, Border.RenderSize
has already a value, even when RenderSize.ActualSize
might still be zero. I guess the reason is that the size of the Border does not depend on Window.Content
, but only on the size of the window (unless, of course, if Window.SizeToContent
is used).
I recommend to place your code into the Window.SizeChanged
event. Because each time the Window size changes, your content needs to change too. You cannot use the size provided in the event parameters, which gives you the size of the complete window, but you can get the the available size within the window like this:
var h = ((Border)GetVisualChild(0)).RenderSize.Height;
You can use that line of code also if you override Windows.OnRender()
.