In my XAML I have this StackLayout:
We can use HeightRequest
, but keep in mind that it is just a request. If Xamarin.Forms doesn't have enough pixels/points to fulfill the request, it will make a best effort.
After changing HeightRequest
, we will need to tell Xamarin.Forms to redraw the StackLayout
and the ContentPage
by calling ForceLayout()
;
public partial class MyContentPage : ContentPage
{
...
void ResizeFooterWrapper(double heightRequest)
{
// Ensure resizing is marshaled to the UI Thread
Device.BeginInvokeOnMainThread(() =>
{
FooterWrapper.HeightRequest = heightRequest;
FooterWrapper.ForceLayout();
this.ForceLayout();
});
}
}
Link to Sample App: https://github.com/brminnick/DynamicStackLayoutSize/
using System;
using Xamarin.Forms;
namespace DynamicStackLayoutSize
{
public class App : Application
{
public App() => MainPage = new MyPage();
}
class MyPage : ContentPage
{
readonly StackLayout _adjustableStackLayout;
public MyPage()
{
_adjustableStackLayout = new StackLayout
{
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.Center,
BackgroundColor = Color.Green,
Children = {
new Label{ Text = "Hello" },
new Label{ Text = "World" }
}
};
var resizeButton = new Button { Text = "Resize" };
resizeButton.Clicked += (s, e) =>
{
if (_adjustableStackLayout.HeightRequest == 196)
ResizeStackLayout(-1);
else
ResizeStackLayout(196);
};
Content = new StackLayout
{
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.Center,
BackgroundColor = Color.Red,
Children ={
_adjustableStackLayout,
resizeButton
}
};
}
void ResizeStackLayout(double heightRequest)
{
Device.BeginInvokeOnMainThread(() =>
{
_adjustableStackLayout.HeightRequest = heightRequest;
_adjustableStackLayout.ForceLayout();
this.ForceLayout();
});
}
}
}