gpt4 book ai didi

c# - 在 Xamarin.Forms 中添加方向更改布局

转载 作者:可可西里 更新时间:2023-11-01 05:35:06 25 4
gpt4 key购买 nike

我需要实现的是,在将屏幕从纵向更改为横向时向现有页面添加布局。我已经设法使用 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 中添加一个新标签。我怎样才能以正确的方式实现它?

提前致谢

最佳答案

On Size allocated 在方向改变时调用多次。我认为您必须进行更多验证,例如检查 child 的数量以避免重复 View 。

    if(landscapecontent.Children.Count>1)
{
//Don't add any views
}

只要我尝试过,就没有用于轮换的事件处理程序。当方向改变时,它在代码中有点 hack 来改变 View 。

即使您可以使用已接受的答案 here .. 希望它能满足您的目的..

关于c# - 在 Xamarin.Forms 中添加方向更改布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24969854/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com