Yehor Hromadskyi
Yehor Hromadskyi

Reputation: 3398

Get the size of hidden view - Xamarin.Forms

I have an empty ContentPage with Grid inside:

    <Grid
        x:Name="YellowGrid"
        BackgroundColor="Yellow">
        <Label 
            Text="It's a Yellow Grid"
            VerticalOptions="Center"
            HorizontalOptions="Center"
            />
    </Grid>

In the overridden method I can get the actual size of a grid:

    protected override void OnSizeAllocated(double width, double height)
    {
        base.OnSizeAllocated(width, height);
        // YellowGrid.Width equals to the width of the screen
    }

And that's okay. But if I will set grid property IsVisible=false, than the Width of the YellowGrid equals -1(that's logical as well). But is it possible to get the required size of a grid if it hidden?

UPDATE

I tried next:

    protected override void OnSizeAllocated(double width, double height)
    {
        base.OnSizeAllocated(width, height);
        var size = YellowGrid.Measure(width, height, MeasureFlags.None);
    }

But Measure for YellowGrid returned required size for Label instead of whole size that grid will place.

Upvotes: 3

Views: 1371

Answers (2)

Yehor Hromadskyi
Yehor Hromadskyi

Reputation: 3398

I used Opacity=0 with InputTransparent=true instead of IsVisible=false to reach the same result of hidden grid:

<Grid
    x:Name="YellowGrid"
    Opacity="0"
    InputTransparent="True"
    BackgroundColor="Yellow">
    <Label 
        Text="It's a Yellow Grid"
        VerticalOptions="Center"
        HorizontalOptions="Center"
        />
</Grid>

Upvotes: 2

Andrii Krupka
Andrii Krupka

Reputation: 4306

You can use Xamarin.Forms.VisualElement.Measure method which determines size request for your control.

Upvotes: 3

Related Questions