在我的XAML中,我有这个StackLayout:
<StackLayout x:Name="FooterWrapper"
Spacing="0"
VerticalOptions="FillAndExpand"
HorizontalOptions="FillAndExpand"
BackgroundColor="Transparent">
<BoxView BackgroundColor="Transparent"
HorizontalOptions="Center"
VerticalOptions="CenterAndExpand"
x:Name="can_applyComplete_topspace" />
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width=".07*" />
<ColumnDefinition Width=".86*" />
<ColumnDefinition Width=".07*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height=".40*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<controls:AndroidButton x:Name="can_applycomplete_gotitbtn"
Grid.Row="0"
Text="{Binding SkipButtonText}"
StyleId="uit_can_applycomplete_gotitbtn"
FontFamily="Avenir Next"
BackgroundColor="White"
Grid.Column="1"
HorizontalOptions="FillAndExpand"
VerticalOptions="Fill"
TextColor="Black"
Clicked="Handle_SkipClicked" />
<controls:CustomLabel Grid.Row="1"
Grid.Column="1"
Text="{i18n:TranslateExtension Text= res_cand_candjobcompliance_profilereachedlbl_list_footer}"
VerticalOptions="Center"
IsVisible="{Binding IsFooterVisible}"
x:Name="cand_candjobcompliance_profilereachedlbl_list_footer"
StyleId="uit_cand_candjobcompliance_profilereachedlbl_list_footer"
TextColor="White"
FontSize="13" />
</Grid>
</StackLayout>
我需要动态控制StackLayout的高度
在OnAppearing中,我为stacklayout设置了特定的高度
FooterWrapper.HeightRequest = 196
在iOS工作中,My new Height设置为视图,但在android中我的高度被忽略。
答案 0 :(得分:6)
我们可以使用HeightRequest
,但请记住它只是一个请求。如果Xamarin.Forms没有足够的像素/点来满足请求,那么它将尽最大努力。
更改HeightRequest
后,我们需要通过调用StackLayout
告诉Xamarin.Forms重绘ContentPage
和ForceLayout()
;
public partial class MyContentPage : ContentPage
{
...
void ResizeFooterWrapper(double heightRequest)
{
Device.BeginInvokeOnMainThread(() =>
{
FooterWrapper.HeightRequest = heightRequest;
FooterWrapper.ForceLayout();
this.ForceLayout();
}
}
}
链接到示例应用: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();
});
}
}
}