Search code examples
c#.netxamlandroid-layoutmaui

Width and Height of Element .net MAUI always NaN


I have a problem getting the actual width and height of an element in maui. In WPF, I have ActualWidth and ActualHeight which give the rendered size of the element, once the element is loaded. But in maui it is always NaN. I have a simple Grid like:

<Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="35*"/>
            <RowDefinition Height="30*"/>
            <RowDefinition Height="35*"/>
        </Grid.RowDefinitions>
        <Border Grid.Row="0" VerticalOptions="Fill" HorizontalOptions="Fill"/>

        <Grid Grid.Row="1">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="20*"/>
                <ColumnDefinition Width="60*"/>
                <ColumnDefinition Width="20*"/>
            </Grid.ColumnDefinitions>

            <Border Grid.Column="0" VerticalOptions="Fill" HorizontalOptions="Fill"/>
            <Border x:Name="CenterBorder" Grid.Column="1" VerticalOptions="Fill" HorizontalOptions="Fill"/>
            <Border Grid.Column="2" VerticalOptions="Fill" HorizontalOptions="Fill" />
        </Grid>

        <Border Grid.Row="2" VerticalOptions="Fill" HorizontalOptions="Fill"/>
</Grid>

Now, I just want to get the rendered width and height of "CenterBorder". But the values are never set. I think it has something to do with the layout is completely dynamic but I do not want to use fixed sizes.


Solution

  • This is because you try to get its Height and Width before the app layout the view. You can try to get it in the page's LayoutChildren method.

        protected override void LayoutChildren(double x, double y, double width, double height)
        {
            base.LayoutChildren(x, y, width, height);
            var width = CenterBorder.Width;
            var height = CenterBorder.Height;
        }