我需要实现的是,在将屏幕从纵向更改为横向时将布局添加到现有页面。我已经设法使用void OnSizeAllocated(double width, double height)检测到方向变化。但我无法在此事件上添加布局。
我的示例 C# 代码是
public class MyLayoutView : ContentPage
{
StackLayout portraitcontent = null;
StackLayout landscapecontent = null;
StackLayout footer = null;
public MyLayoutView ()
{
portraitcontent = new StackLayout ();
landscapecontent = new StackLayout ();
footer = new StackLayout ();
this.Padding = new Thickness(0, Device.OnPlatform(20, 0, 0), 0, 0);
this.BackgroundColor = Color.FromHex ("#ffffff");
this.Content = new StackLayout
{
Children =
{
portraitcontent ,
landscapecontent ,
footer
}
};
}
}
OnSizeAllocated 方法
protected override void OnSizeAllocated(double width, double height)
{
base.OnSizeAllocated(width, height);
if (width < height) {
// In Portrait
portraitcontent .IsVisible = true;
landscapecontent.IsVisible = false;
Debug.WriteLine ("Application Is in portrait");
} else {
// In Landscape
portraitcontent .IsVisible = false;
landscapecontent.IsVisible = true;
landscapecontent.Children.Clear ();
Label LandscapeLabel= new Label
{
Text = "<Each Time Text Changes>",
HorizontalOptions = LayoutOptions.StartAndExpand,
TextColor=Xamarin.Forms.Color.FromHex("#000000")
};
landscapecontent.Children.Add(LandscapeLabel);
Debug.WriteLine ("Application Is in Landscape");
}
}
它抛出无法修改集合,而重新进入被阻止错误。每次方向更改时,我都需要在 stacklayout 中添加一个新标签。我怎样才能以适当的方式实现它?
提前致谢