C# Xamarin在顶部和底部形成相对布局约束
我是新来的C# Xamarin在顶部和底部形成相对布局约束,c#,macos,visual-studio,xamarin.forms,C#,Macos,Visual Studio,Xamarin.forms,我是新来的Xamarin.Forms(Swift是我的强项)。为了让我的应用程序在所有屏幕大小上都能正常工作,我使用了RelativeLayout。唯一的问题是,我只能找到如何设置宽度和高度 我想做的是设置顶部和底部约束 这是我在Swift中可以做的: let redBox=UIView() redBox.translatesAutoResizezingMaskintoConstraints=false redBox.backgroundColor=.red 让blueBox=UIView()
Xamarin.Forms
(Swift
是我的强项)。为了让我的应用程序在所有屏幕大小上都能正常工作,我使用了RelativeLayout
。唯一的问题是,我只能找到如何设置宽度和高度
我想做的是设置顶部和底部约束
这是我在Swift中可以做的:
let redBox=UIView()
redBox.translatesAutoResizezingMaskintoConstraints=false
redBox.backgroundColor=.red
让blueBox=UIView()
blueBox.translatesAutoResizezingMaskintoConstraints=false
blueBox.backgroundColor=.blue
view.addSubview(红色框)
view.addSubview(blueBox)
redBox.widthAnchor.constraint(equalTo:view.widthAnchor).isActive=true
redBox.topAnchor.constraint(equalTo:view.topAnchor).isActive=true
redBox.heightAnchor.constraint(equalToConstant:150).isActive=true
blueBox.widthAnchor.constraint(equalTo:view.widthAnchor).isActive=true
blueBox.topAnchor.constraint(equalTo:redBox.bottomAnchor).isActive=true
blueBox.bottomAnchor.constraint(equalTo:view.bottomAnchor).isActive=true
这将导致出现以下屏幕:
如何在Xamarin.Forms
中实现这一点?
我只能找到如何进行宽度和高度约束。我还想通过编程来完成它,而不是XAML
或拖放
这是我找到的Xamarin.Forms代码:
var布局=新的RelativeLayout();
内容=布局;
var aquaBox=new-BoxView()
{
颜色=Color.Aqua
};
var silverBox=new-BoxView
{
颜色=颜色。银色
};
aquaBox.HeightRequest=150;
布局。子项。添加(水族箱,
widthConstraint:Constraint.RelativeToParent(parent=>parent.Width)
);
layout.Children.Add(silverBox,
yConstraint:Constraint.RelativeToView(aquaBox,(RelativeLayout,element)=>element.Height)
);
XAML
:
该代码的结果是:
需要什么C#
Xamarin.Forms
code才能获得与我使用Swift
相同的视图
注意:我想要
Xamarin.Forms
code,而不是针对Android
、Windows
和iOS
的单独代码,我不知道如何使用相对论来实现它,但是使用网格
很容易
var aquaBox = new BoxView
{
Color = Color.Aqua,
HeightRequest = 150
};
var silverBox = new BoxView
{
Color = Color.Silver
};
var grid = new Grid { RowSpacing = 0 };
grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto});
grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Star });
grid.Children.Add(aquaBox, 0, 0);
grid.Children.Add(silverBox, 0, 1);
Content = grid;
RelativeLayout
:
在heightConstraint
参数中查找高度。RelativeLayout
的VerticalOptions
是默认的Fill
,当视图(即RelativeLayout
)调整大小时,将重新计算父视图的高度
var layout = new RelativeLayout(); //VerticalOptions is default Fill
var aquaBox = new BoxView
{
Color = Color.Aqua,
HeightRequest = 150
};
var silverBox = new BoxView
{
Color = Color.Silver
};
layout.Children.Add(aquaBox,
widthConstraint: Constraint.RelativeToParent((parent) => parent.Width)
);
layout.Children.Add(silverBox,
widthConstraint: Constraint.RelativeToParent((parent) => parent.Width),
yConstraint: Constraint.RelativeToView(aquaBox, (parent, sibling) => sibling.Height),
heightConstraint: Constraint.RelativeToParent((parent) => parent.Height - aquaBox.HeightRequest)
);
Content = layout;