是否可以在设置一次后更改RelativeLayout
的约束?Xamarin.Forms:事后更改RelativeLayout约束
在文档中我看到像GetBoundsConstraint(BindableObject)
这样的方法,但我认为只有拥有XAML文件时才能使用它们。现在我试图在代码中这样做。我得到null
如果我尝试
RelativeLayout.GetBoundsConstraint(this.label);
我发现的唯一方法是从布局中删除的孩子,以新的约束重新添加。
例子:
public class TestPage : ContentPage
{
private RelativeLayout relativeLayout;
private BoxView view;
private bool moreWidth = false;
public TestPage()
{
this.view = new BoxView
{
BackgroundColor = Color.Yellow,
};
Button button = new Button
{
Text = "change",
TextColor = Color.Black,
};
button.Clicked += Button_Clicked;
this.relativeLayout = new RelativeLayout();
this.relativeLayout.Children.Add(this.view,
Constraint.Constant(0),
Constraint.Constant(0),
Constraint.Constant(80),
Constraint.RelativeToParent((parent) =>
{
return parent.Height;
}));
this.relativeLayout.Children.Add(button,
Constraint.RelativeToParent((parent) =>
{
return parent.Width/2;
}),
Constraint.RelativeToParent((parent) =>
{
return parent.Height/2;
}));
this.Content = this.relativeLayout;
}
private void Button_Clicked(object sender, EventArgs e)
{
double width = 0;
if(this.moreWidth)
{
width = 120;
}
else
{
width = 80;
}
var c= BoundsConstraint.FromExpression((Expression<Func<Rectangle>>)(() => new Rectangle(0, 0, width, this.Content.Height)), new View[0]);
RelativeLayout.SetBoundsConstraint(this.view, c);
this.relativeLayout.ForceLayout();
this.moreWidth = !this.moreWidth;
}
}
感谢您的出色答案!是否可以将'BoundsConstraint.FromExpression'和'Constraint.RelativeToParent'一起使用?或者你可以只设置'矩形'的值?我想要做的是改变占用屏幕一半的元素的宽度。因此你必须知道父母的身高。目前我正在使用'this.Content.Height',这似乎工作。尽管我必须进一步测试它。 – testing
只要所修改的项目的所有约束都是Constant或RelativeToParent(BoundsConstraint是所有四个x/y /宽度/高度约束的组合,所有这些都必须满足此条件标准)。如果它们中的任何一个使用RelativeToView,则需要将数组中的这些视图作为第二个参数传递给'FromExpression()'。尽管如此,除非您尝试过,否则这种攻击只能用于Constant,但很难说清楚。当然,这取决于内部,因此可能会打破下一个XF版本。 –
我试图使用'RelativeToParent',但努力使用正确的符号。我尝试使用'Constraint.RelativeToParent((parent)=> {return parent.Height;})'而不是常量,但我得到了一个消息,如*太多参数*。你有工作吗? – testing