WPF用按钮填充堆栈面板?

时间:2018-10-11 10:02:37

标签: c# wpf

我在运行时创建按钮,计算StackPanel的大小并除以按钮大小,然后将按钮添加到StackPanel。

现在我希望最终结果看起来像这样:

********
**BBBB**
**BBBB**
**BBBB**
********

现在,有了StackPanel,我得到了:

********
**    **
**BBBB**
**    **
********

StackPanel是否可以正确控制以进行此类工作?

下面的代码用于另一个StackPanel(有效),但是按钮是垂直添加的:

*****
**B**
**B**
**B**
*****

这在Program.cs中

 private void addButtonGrp()
    {

        //Calculate size of container to determine number of buttons
        int btnMinimumHeightSize = 30;
        int btnNumberCreated = (Convert.ToInt16(rctGrupe.Height) / btnMinimumHeightSize);  

        for (int i = 0; i < btnNumberCreated ; i++)
        {


            CreateGroupButtons btn = new CreateGroupButtons();
            var btnX = new Button();

            btnX=(btn.addButton(i,btnMinimumHeightSize,Convert.ToInt16(stPanel.Width)));
            btnX.Click += ClickHandler2;

            if (i==btnNumberCreated -1 )
            {
                btnX.Height = btnMinimumHeightSize + ((Convert.ToDouble(rctGrupe.Height) / btnMinimumHeightSize) % 1)*(btnNumberCreated);
            }

            stPanel.Children.Add(btnX);
        }
    }

这是在CreateGroupButtons类中

public Button addButton(int num, int btnHeight, int btnWidth)
    {

        var btnX = new Button { Content = "Group " + num, Tag = num, Height = btnHeight, Width=btnWidth };
        return btnX;
    }

1 个答案:

答案 0 :(得分:3)

这是一个用4x3的Button网格填充UniformGrid的基本示例:

<ItemsControl x:Name="buttonGrid">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <UniformGrid Columns="4"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Button Content="{Binding}" ContentStringFormat="Group {0}"
                    Click="ClickHandler2"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

将ItemsSource属性设置为IEnumerable<int>,如下所示:

buttonGrid.ItemsSource = Enumerable.Range(1, 12);