![](/img/trans.png)
[英]How to add empty UserControl of StackPanel programmatically in WPF
[英]how to wrap dynamic button in stackpanel programmatically? [WPF]
我想以編程方式在堆棧面板中以4行4列的形式添加16個按鈕。 當我在堆棧面板中添加按鈕時,我只能查看其中的4個按鈕。 我無法包裝它。 我不想使用換行面板來解決此問題。(當窗口最大化時,換行面板會導致問題)。
這是我的代碼,
foreach (var buttonName in list)
{
Button newButton = new Button(){Content = "button_name"};
this.mainPanel.Children.Add(newButton);
}
XML,
<StackPanel x:Name="mainPanel" Orientation="Horizontal"/>
最后,我完成了。 感謝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;
}
}
}
這就是您所需要的:
UniformGrid g = new UniformGrid(){ Rows = 4, Columns = 4};
g.Children.Add(new Button());
... add your 16 buttons ...
UniformGrid知道如何將其內容表示為(行x列)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.