设置按钮变量的列范围

时间:2018-08-02 09:05:05

标签: c# xamarin xamarin.forms

我已经在Xamarin应用程序中创建了一个网格,该网格具有4行24列。

我有12个使用相同属性的按钮,因此,为了避免自己分别创建全部12个按钮,我这样做了

var functionButton = new Style(typeof(Button))
     {
        Setters = {
                new Setter { Property = BackgroundColorProperty, Value = Color.FromHex ("#F0E68C") },
                new Setter { Property = Button.TextColorProperty, Value = Color.Black },
                new Setter { Property = Button.CornerRadiusProperty, Value = 0 },
                new Setter { Property = Button.FontSizeProperty, Value = 10 }
        }
      };

然后按如下所示将它们添加到网格中

controlGrid.Children.Add(new Button { Text = "End" + Environment.NewLine + "Sale", Style = functionButton }, 0, 0);
controlGrid.Children.Add(new Button { Text = "Repeat" + Environment.NewLine + "  Last", Style = functionButton }, 1, 0);
controlGrid.Children.Add(new Button { Text = "Void" + Environment.NewLine + "Line", Style = functionButton }, 2, 0);

依此类推,直到添加了全部12个。

但是,我希望每个按钮占用2列。

通常,如果我分别创建按钮,则可以使用Grid.SetColumnSpan(Button1, 2);

但这似乎效率不高,因为我需要分别创建所有12个按钮。还有另一种方法可以使用这种创建当前按钮的方法来设置列跨度吗?

1 个答案:

答案 0 :(得分:1)

您可以使用for循环。

var btnLabels = new[] {
    "End" + Environment.NewLine + "Sale",
    "Repeat" + Environment.NewLine + "  Last",
    "Void" + Environment.NewLine + "Line"
};

Button buttonCtrl;
for (int row= 0; row < btnLabels.Length; row++)
{
    buttonCtrl = new Button { Text = btnLabels[row], Style = functionButton };
    Grid.SetColumnSpan(btn, 2);
    controlGrid.Children.Add(btn, row, 0);
}