Search code examples
c#xamlxamarinxamarin.formsxamarin.essentials

How to Bind a visual element HeightRequest which is inside a ScrollView to equal to the Height of the Page?


I'm trying to set a BoxView's Height to the Height of the page (I'm using Xamarin Essentials for this). The BoxView is contained in a StackLayout and that StackLayout is contained in a ScrollView like this:

<ScrollView Orientation="Vertical">
    <StackLayout>
        <BoxView HeightRequest="{Binding height}" x:Name="TestBox" BackgroundColor="Orange" />
        <BoxView BackgroundColor="Red" HeightRequest="200" />
    </StackLayout>
</ScrollView>

The HeightRequest of the BoxView is being defined in my Code Behind.

I've tried setting this variable to the height of the device in my OnAppearing() and in the Page's constructor, but both times the boxview does not fill the whole page, here is what i have tried:

public Double height;

public MainPage()
{  
    InitializeComponent();
    height = DeviceDisplay.MainDisplayInfo.Height / DeviceDisplay.MainDisplayInfo.Density;
}

The result:

Example

I've also tried adding the following after i set the Height, but this didn't worked either:

this.ForceLayout();

I do however, get my desired result if I manually set the HeightRequest (However, this would only work on my specific device):

<BoxView HeightRequest="720" x:Name="TestBox" BackgroundColor="Orange" />

How can i bind the Height of the BoxView to the Height of the page if the BoxView is cointained inside a ScrollView?


Solution

  • You did not set the bindingContext in code behind so the HeightRequest="{Binding height}" will not work.

    Also, remember that you should define the height as a Property.

    public partial class MainPage : ContentPage
    {
    
        public Double height { get; set; }
    
        public MainPage()
        {
            InitializeComponent();
    
            height = DeviceDisplay.MainDisplayInfo.Height / DeviceDisplay.MainDisplayInfo.Density;
    
            BindingContext = this;
        }
    }
    

    I did a test, after adding the bindingContext and define the height as a Property, you codes works well:).