如何在运行时在xamarin.forms中更改相对布局中视图的位置或大小

问题描述 投票:0回答:1

我做的是通过设置所有约束我为相对布局添加了标签。

下面是我的代码。

relativeLayout.Children.Add(textLabel, Constraint.RelativeToView(innerBorderBox, (parent, sibling) =>
    {
        return sibling.Width * 0.55;
    }), Constraint.RelativeToView(innerBorderBox, (parent, sibling) =>
    {
        return sibling.Y;
    }), Constraint.RelativeToView(innerBorderBox, (parent, sibling) =>
    {
        return sibling.Width * .45;
    }), Constraint.RelativeToView(innerBorderBox, (parent, sibling) =>
    {
        return sibling.Height;
    }));

它完美地运作。

现在我想动态更改该标签(textLabel)X Constraint和Width Constraint。例如,从上面的代码X Constraint是sibling.Width * 0.55,宽度是sibling.Width * .45,然后需要更改为X为sibling.Width * 0.55 + 10,宽度为sibling.Width * .45 - 50。怎么做?

我的猜测是,它可以通过删除相对布局的标签并再次添加到具有新约束的相对布局来完成。但我认为会有更好的解决方案。

c# xamarin xamarin.forms constraints relativelayout
1个回答
1
投票

正如@ LeoZhu-MSFT评论,它对我来说非常适合。这是我如何解决问题

对于我的问题,

现在我想动态更改该标签(textLabel)X Constraint和Width Constraint。例如,从上面的代码X Constraint是sibling.Width * 0.55,宽度是sibling.Width * .45,然后需要更改为X为sibling.Width * 0.55 + 10,宽度为sibling.Width * .45 - 50 。 怎么做?

更改X约束

 RelativeLayout.SetXConstraint(textLabel, Constraint.RelativeToView(innerBorderBox, (parent, sibling) =>
 {
    return sibling.Width * 0.55 + 10;
 }));

更改宽度约束

 RelativeLayout.SetWidthConstraint(textLabel, Constraint.RelativeToView(innerBorderBox, (parent, sibling) =>
 {
    return sibling.Width * .45 - 50;
 }));

有关详细信息

RelativeLayout.SetWidthConstraint => https://docs.microsoft.com/en-us/dotnet/api/xamarin.forms.relativelayout.setwidthconstraint?view=xamarin-forms RelativeLayout.SetXConstraint => https://docs.microsoft.com/en-us/dotnet/api/xamarin.forms.relativelayout.setxconstraint?view=xamarin-forms

© www.soinside.com 2019 - 2024. All rights reserved.