问题描述
您好我可以问一个问题吗?我试图在StackPanel添加Columns,但我不知道如何使这个解决方案工作。
Hello can I ask a question? I tried to add Columns at StackPanel, but I've not idea, how to make this solution work.
//xaml
<Grid>
<StackPanel x:Name="sp">
<Grid x:Name="GridPanel" Grid.Row="0" Grid.Column="0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
</Grid>
</StackPanel>
</Grid>
//C#
TextBox tb = new TextBox();
tb.Height = 60;
tb.Width = 100;
Grid.SetRow(tb, 0);
Grid.SetColumn(tb, 0);
//this.GridPanel.Children.Add(tb);
Button b = new Button();
b.Content = "Button";
b.Width = 100;
b.Height = 60;
b.Click += new RoutedEventHandler(new_but);
Grid.SetRow(b,0);
Grid.SetColumn(b,1);
//this.GridPanel.Children.Add(b);
如何添加列,我用 this.sp.Children.Add
推荐答案
sp.Children.Add(UIElement); // Adds a new element "in the stack"
你需要使用这段代码,
Whereas you need to use this code,
foreach (var child in sp.Children) {
// check the type of children
if(child is Grid) {
// the grid, which supports columns.
// Now, add columns to the "child".
}
}
阅读这篇文章,了解如何添加以编程方式将列和行添加到网格。 []
现在,当你改变定义时 child
,它会改变StackPanel中存在的网格。我可以问,为什么当一切都必须在网格中时,你甚至使用StackPanel。 Grid已作为此StackPanel的父级存在。
Read this post to learn how to add columns and rows to Grid programmatically. https://social.msdn.microsoft.com/Forums/vstudio/en-US/18a54950-436d-4195-84a0-e2c7835c19dd/programmatically-add-column-and-rows-to-grid-and-add-the-button-control-in-each-cell?forum=wpf[^]
Now, when you will alter the definition of child
, it would alter the grid that is present inside the StackPanel. Can I ask, why are you even using a StackPanel when everything has to be in a Grid. Grid is already present as a parent for this StackPanel.
这篇关于如何在StackPanel添加列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!