我想在堆栈面板中以编程方式以4行4列的形式添加16个按钮。当我在堆栈面板中添加我的按钮时,我只能查看其中的4个按钮。我无法包装它。我不想使用wrap面板来解决问题。(当窗口最大化时,Wrap面板会导致问题。)
这是我的代码,
foreach (var buttonName in list)
{
Button newButton = new Button(){Content = "button_name"};
this.mainPanel.Children.Add(newButton);
}
XML,
<StackPanel x:Name="mainPanel" Orientation="Horizontal"/>
答案 0 :(得分:0)
最后,我做到了。感谢M.kazem Akhgary建议将网格作为解决方案。
GridLengthConverter gridLengthConverter = new GridLengthConverter();
RowDefinition row1 = new RowDefinition();
row1.Height = (GridLength)gridLengthConverter.ConvertFrom("*");
RowDefinition row2 = new RowDefinition();
row2.Height = (GridLength)gridLengthConverter.ConvertFrom("*");
RowDefinition row3 = new RowDefinition();
row3.Height = (GridLength)gridLengthConverter.ConvertFrom("*");
RowDefinition row4 = new RowDefinition();
row4.Height = (GridLength)gridLengthConverter.ConvertFrom("*");
mainPanel.RowDefinitions.Add(row1);
mainPanel.RowDefinitions.Add(row2);
mainPanel.RowDefinitions.Add(row3);
mainPanel.RowDefinitions.Add(row4);
ColumnDefinition col1 = new ColumnDefinition();
col1.Width = (GridLength)gridLengthConverter.ConvertFrom("*");
ColumnDefinition col2 = new ColumnDefinition();
col2.Width = (GridLength)gridLengthConverter.ConvertFrom("*");
ColumnDefinition col3 = new ColumnDefinition();
col3.Width = (GridLength)gridLengthConverter.ConvertFrom("*");
ColumnDefinition col4 = new ColumnDefinition();
col4.Width = (GridLength)gridLengthConverter.ConvertFrom("*");
mainPanel.ColumnDefinitions.Add(col1);
mainPanel.ColumnDefinitions.Add(col2);
mainPanel.ColumnDefinitions.Add(col3);
mainPanel.ColumnDefinitions.Add(col4);
int row = 0;
int col = 0;
foreach (var buttonName in List)
{
if(row<=4)
{
if (col <= 4)
{
Button newButton = new Button()
{
Content = buttonName.Name,
};
Grid.SetRow(newButton, row);
Grid.SetColumn(newButton, col);
col++;
this.mainPanel.Children.Add(newButton);
}
else
{
row++;
col = 0;
}
}
}
答案 1 :(得分:0)
这就是你所需要的:
UniformGrid g = new UniformGrid(){ Rows = 4, Columns = 4};
g.Children.Add(new Button());
... add your 16 buttons ...
UniformGrid知道如何将其内容呈现为(行x列)。