Why is my Grid's width NaN?

ProfK picture ProfK · Apr 4, 2014 · Viewed 20.4k times · Source

I have the following mark-up in a view. When I get WindowContainer.Width during start-up code for the view, it returns NaN.

<Border BorderThickness="10">
  <StackPanel x:Name="Panel" Orientation="Vertical" >
    <Grid x:Name="WindowContainer" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Loaded="WindowContainer_OnLoaded">
      <delphi:Win32WindowHost x:Name="Host" />
    </Grid>
    <TextBlock x:Name="InfoTextBlock" HorizontalAlignment="Right" />
  </StackPanel>
</Border>

Does Stretch make the grid stretch to accomodate all its content, or to fill its container? I want it to stretch to fill the container, the Border, and have a proper double width I can use to size a floating window to be the same size.

Answer

Anatoliy Nikolaev picture Anatoliy Nikolaev · Apr 4, 2014

Does Stretch make the grid stretch to accomodate all its content, or to fill its container?

From MSDN about HorizontalAlignment="Stretch":

Child elements are stretched to fill the parent element's allocated layout space. Explicit Width and Height values take precedence.


Why is my Grid's width NaN?

NaN is to mean "not set". FrameworkElement is the base class for many Controls in WPF and if you do not explicitly set the Height and Width properties then in the class constructor will be a default value of NaN.


When I get WindowContainer.Width during start-up code for the view, it returns NaN

In this case try get the ActualWidth, instead of Width, because:

ActualWidth property is a calculated value based on other width inputs, and the layout system. The value is set by the layout system itself, based on an actual rendering pass, and may therefore lag slightly behind the set value of properties such as Width that are the basis of the input change.