通过C#代码添加多个堆栈面板

本文关键字:堆栈 代码 添加 通过 | 更新日期: 2023-09-27 18:27:08

我有一个有多个孩子的妈妈。每个子项都已经分配了一个名称,并且需要用户输入该值。

我试图通过代码为每个孩子生成一个带有TextBlock和TextBox的StackPanel。孩子的数量是未知的,所以我需要一个循环来创建每个StackPanel,并将它们添加到添加到Border控件的"妈妈"StackPanel中。当我运行代码时,它会很好地运行整个循环,但它不会在显示中显示任何内容。

这是代码:

var momStackPanel = new StackPanel() { Orientation = Windows.UI.Xaml.Controls.Orientation.Vertical};
foreach (ChildItem item in ChildList)
{
    var childItemSP = new StackPanel();childItemSP.Orientation = Orientation.Horizontal;
    TextBlock nameTB = new TextBlock();
    name.Text = item.Name;
    childItemSP.Children.Add(nameTB);
    TextBox valueTB = new TextBox();
    valueTB .Text = item.Value;
    childItemSP.Children.Add(valueTB);
}
BorderSection.Child = momStackPanel;
BorderSection.Visibility = Windows.UI.Xaml.Visibility.Visible;

这是XAML:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition  Height="Auto" />
        <RowDefinition  Height="Auto"/>
        <RowDefinition  Height="Auto"/>
        <RowDefinition  Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <TextBlock  x:Name="t4"  Text="t4"  Grid.Row="0"/>
    <Border Grid.Row="1"  HorizontalAlignment="Stretch">
                <StackPanel >
                    <TextBlock x:Name="r1" Text="{Binding r1}"  HorizontalAlignment="Center" />
                    <TextBlock x:Name="r2" Text="r2" Foreground="DarkGray"/>
                </StackPanel>               
    </Border>
    <Border x:Name="BorderSection" Grid.Row="2">            
    </Border>
    <StackPanel x:Name="CommentPanel" Orientation="Vertical" Grid.Row="3" Margin="6,6,6,6">
        <TextBox x:Name="Comment" Text="" MinHeight="100"/>
    </StackPanel>
    <StackPanel Orientation="Horizontal" >
        <Button x:Name="Submit" Content="Submit" Click="Submit_Click_1"/>
        <Button x:Name="Cancel" Content="Cancel" Click="Cancel_Click_1"/>
    </StackPanel>
</Grid>

有什么办法吗?

通过C#代码添加多个堆栈面板

ItemsControl控件的作用类似于具有可变项目数的StackPanel。您可以将它绑定到一个ObservableCollection,这样您就不必在后面的代码中破坏视图。

<ItemsControl ItemsSource="{Binding Children}">
    <ItemsControl.Resources>
        <ResourceDictionary Source="ChildTemplate.xaml"/>
    </ItemsControl.Resources>
</ItemsControl>

然后,您可以在一个单独的文件(ChildTemplate.xaml)中提供子级视图

<DataTemplate DataType="{x:Type myNamespace:ChildViewModel}">
    <StackPanel >
        <TextBlock Text="{Binding Name}" />
        <TextBlock Text="{Binding Value}" />
    </StackPanel> 
</DataTemplate>

不要忘记,无论何时更改ObservableCollection,都必须调用OnPropertyChanged。

相关文章: