【问题标题】:Generic method that programatically returns a layout constraint based on Relative Layout c#以编程方式返回基于相对布局 c# 的布局约束的通用方法
【发布时间】:2018-02-19 19:35:46
【问题描述】:

我有一个视图,在这个视图中,我在代码中添加组件而不是使用 xaml,我有一个相对布局和一个创建标签 Lbl 和一个按钮 MyButton 作为参数传递的类 width,height,img source, label text and color.

var innerLayout = new RelativeLayout() { BackgroundColor = Color.Black };
var myCustomhBtn = new Custom(100, 120, "img.png", "the text of label", Color.White);

现在我想将xConstraintyConstraint 添加到每个组件中。 它们都将是表单中的 x 和 y 约束:

            innerLayout.Children.Add(  
            myCustomhBtn.MyButton,
            xConstraint: Constraint.RelativeToParent((parent) => {
                double x1 = parent.Width / 2 - myCustomhBtn.MyButton.Radius;
                double x2 = parent.Width - 2 * myCustomhBtn.MyButton.Radius;
                return (x1 + x2) / 2 + myCustomhBtn.MyButton.Radius/ 2;
            }),
            yConstraint: Constraint.RelativeToParent((parent) => {
                double y1 = 0;
                double y2 = parent.Height / 2 - 2 * myCustomhBtn.MyButton.Radius;
                return (y1 + y2) / 2 - myCustomhBtn.MyButton.Radius;
            }));
        innerLayout.Children.Add(
            myCustomhBtn.Lbl,
            Constraint.RelativeToView(myCustomhBtn.MyButton.Radius, (parent, sibling) => {
                return sibling.X + myCustomhBtn.MyButton.Radius- myCustomhBtn .Lbl.Width / 2;
            }), 
            Constraint.RelativeToView(myCustomhBtn.MyButton.Radius, (parent, sibling) => {
              return sibling.Y - 18;
             }));

对于标签,我只希望它是 -18 的向上按钮 y 和居中的 x

所以基本上我想做类似的事情

var innerLayout = new RelativeLayout() { BackgroundColor = Color.Black };
    var myCustomhBtn = new Custom(100, 120, "img.png", "the text of label", Color.White);
AddComponent(innerlayout, x,y);

但由于每个约束的形式为Func

xConstraint: Constraint.RelativeToParent((parent) => {return xxxx; })

我不知道如何创建泛型方法

怎么做?或者最好的方法是什么?

【问题讨论】:

  • 其实我很难理解你的问题是什么。是什么阻止您将第一个清单中的代码放入方法中?您也可以从该方法创建约束。或者你想通过Func?你也可以毫无问题地做到这一点。
  • 无论如何,我认为您应该考虑您的设计以及如何使用布局。我不知道你想要达到什么目标,但对我来说似乎过于复杂。
  • 我正在添加一些按钮,我只想创建一个接收 x 和 y 的函数,并返回相应的 x 或 y 约束
  • @Paul Kertscher 能否提供一个示例函数,以便我知道这是否是我想要实现的目标?
  • 我试图给出一个答案,但我不知道我是否正确地解决了你的问题。如果我写错了,请评论,我会努力完善。

标签: c# xamarin.forms code-behind


【解决方案1】:

我只想创建一个接收 x 和 y 的函数,并返回相应的 x 或 y 约束

您可以(虽然我不建议这样做)创建一个返回 TupleConstraints 的方法。

private (Constraint xConstraint, Constraint yConstraint) BuildConstraints(x, y)
{
    var xConstraint = Constraint.RelativeToParent(parent => /* whatever ... */);
    var yConstraint = Constraint.RelativeToParent(parent => /* whatever ... */);
    return (xConstraint, yConstraint);
}

但我宁愿为每个约束创建一个方法

Constraint BuildXConstraint(x)
{
    return Constraint.RelativeToParent(parent => /* whatever ... */);
}

【讨论】:

    猜你喜欢
    • 2012-10-01
    • 2018-04-08
    • 2023-03-05
    • 2019-07-30
    • 2017-01-10
    • 2019-06-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-26
    相关资源
    最近更新 更多