0

我有 arraylist.let 说它包含 15 个元素。我将这些添加到堆栈面板。我需要每行添加 3 个元素。我的代码如下。我正在水平或垂直。让我知道如何做到这一点。

    MainWindow w;
    public ShopCart(MainWindow m,ArrayList _list)
    {

        InitializeComponent();
        w = m;


        int i = 1;

        foreach (string cartitems in _list)
        {

                mystackpanel.Orientation = Orientation.Horizontal;
                mystackpanel.Margin.Left.Equals(150);
                Label lbl = new Label();
                lbl.Name = "Label" + i;
                lbl.Height = 30;
                lbl.Width = 200;
                lbl.Margin.Left.Equals(150);
                //lbl.Margin.Top.Equals(150);
                lbl.Content = cartitems.ToString();
                mystackpanel.Children.Add(lbl);
                i++;

                int str = mystackpanel.Children.Count;
                MessageBox.Show(Convert.ToString(str));
                if (str%3 == 0)
                {
                    Button btndelete = new Button();
                    btndelete.Content = "Delete";
                    btndelete.Width = 120;
                    btndelete.Height = 35;
                    mystackpanel.Children.Add(btndelete);

                    mystackpanel.Margin.Top.Equals(500);


                }








        }
4

1 回答 1

1

这是一些示例代码(假设您已经有一个按钮列表,并将在主控件中添加外部堆栈面板)您可以尝试,您可能需要根据需要更改一些内容:

            List<Button> buttons = new List<Button>();
            StackPanel panel = new StackPanel();
            panel.Orientation = Orientation.Horizontal;
            int count = 0;
            StackPanel innerPanel = new StackPanel();
            innerPanel.Orientation = Orientation.Vertical;

            foreach (Button button in buttons)
            {
                innerPanel.Children.Add(button);
                ++count;
                if (count % 3 == 0 && count != 0)
                {
                    panel.Children.Add(innerPanel);
                    innerPanel = new StackPanel();
                    innerPanel.Orientation = Orientation.Vertical;
                }
            }

            if (panel.Children.Contains(innerPanel) == false)
            {
                panel.Children.Add(innerPanel);
            }

尽管在我看来,最好的方法是拥有一个具有 n*n 行和列的 Grid,并将您的按钮添加到相应的行、列。

于 2013-09-21T13:22:36.983 回答