我需要实现的是,在屏幕从竖向变为横向时,向现有页面添加布局。我已经使用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 Method
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中添加一个新标签。有什么适当的方法可以实现吗?
提前感谢。