Xamarin.Forms相对布局奇怪的行为

时间:2015-09-09 20:18:20

标签: xaml xamarin xamarin.forms xamarin-studio

我面临相对布局的问题。 我的目标是创建类似的布局:enter image description here

免责声明:这个应该是相对布局,因为我需要添加一些其他元素,这些元素的位置取决于这两个。

这是我的代码:

var layout = new RelativeLayout();

var box = new BoxView { BackgroundColor = Color.Olive, WidthRequest = 50, HeightRequest = 50 };

var label = new Label
{
    LineBreakMode = LineBreakMode.WordWrap,
    Text = "Here is a lot of text ..... Here is a lot of text";
};
layout.Children.Add(box, Constraint.Constant(10), Constraint.Constant(10));
layout.Children.Add(label,
    Constraint.RelativeToView(box, (relativeLayout, view) => view.X + view.Width + 20),
    Constraint.RelativeToView(box, (relativeLayout, view) => view.Y),
    //Constraint.RelativeToParent(relativeLayout => relativeLayout.Width - 20 - 50 -10));


MainPage = new ContentPage
{
    Content = layout    
};

这是我的问题。如果我没有添加注释行,则标签不在屏幕之外。 就像这里:enter image description here

如果我添加注释字符串(宽度约束),那么还有一件奇怪的事情:文本没有完全显示。我的意思是应该有大约10个单词,但它们会突然消失。 enter image description here

我没有设置任何高度约束,因此不应限制标签的大小。

你可以帮我解决这个问题吗? 谢谢!

1 个答案:

答案 0 :(得分:0)

没有什么可以阻止你在相对布局中利用堆栈的布局。

E.g。

var stackLayout = new StackLayout {
    Orientation = StackOrientation.Horizontal,
    Padding = new Thickness (20, 10, 10, 0),
    Children = {
        new BoxView { 
            BackgroundColor = Color.Olive, 
            WidthRequest = 50, 
            HeightRequest = 50, 
            HorizontalOptions = LayoutOptions.Start,
            VerticalOptions = LayoutOptions.Start
        },
        new Label {
            LineBreakMode = LineBreakMode.WordWrap,
            HorizontalOptions = LayoutOptions.FillAndExpand,
            Text = "Here is a lot of text ..... Here is a lot of textHere is a lot of text ..... Here is a lot of textHere is a lot of text ..... Here is a lot of textHere is a lot of text ..... Here is a lot of textHere is a lot of text ..... Here is a lot of textHere is a lot of text ..... Here is a lot of textHere is a lot of text ..... Here is a lot of textHere is a lot of text ..... Here is a lot of textHere is a lot of text ..... Here is a lot of textHere is a lot of text ..... Here is a lot of textHere is a lot of text ..... Here is a lot of textHere is a lot of text ..... Here is a lot of text"
        }
    }
};

var relLayout = new RelativeLayout ();
relLayout.Children.Add (stackLayout, 
    Constraint.Constant (0), 
    Constraint.Constant (0), 
    Constraint.RelativeToParent((p)=>{return p.Width;}),
    Constraint.RelativeToParent((p)=>{return p.Height;})
);

当然,你需要修改价值观,但基本前提是那里。