如何动态创建和修改新的Grid行元素?

How to dynamically create and modify a new Grid row elements?

我刚刚开始一个新的 WPF 应用程序。 我有一个网格,想动态创建行(例如按一个按钮),然后在该行内创建 TextView/ProgressBar。

我已经搜索过如何以编程方式创建网格行。但是在每个解决方案中,我都无法访问里面的内容,它变得毫无用处。

<Grid x:Name="MainGrid">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <Button x:Name="AddLineButton" Content="Click to add a new line" Click="AddLineButton_Click"/>
    <Grid x:Name="beGrid" Grid.Row="1">
<!-- I need my new rows here -->
    </Grid>
</Grid>
int i = 0; //nb of rows

    private void AddLineButton_Click(object sender, RoutedEventArgs e)
    {
        Create_line();
        i++;
    }

    private void Create_line()
    {
        RowDefinition gridRow = new RowDefinition();
        gridRow.Height = new GridLength(1, GridUnitType.Star);
        beGrid.RowDefinitions.Add(gridRow);
        StackPanel stack = new StackPanel();
        stack.Orientation = Orientation.Horizontal;
        TextBlock textBlock = new TextBlock();
        textBlock.Text = "Question";
        textBlock.Name = "Test" + i.ToString();
        stack.Children.Add(textBlock);
        beGrid.Children.Add(stack);
        Grid.SetRow(stack, i);
    }

我无法访问以前创建的元素。

回答后:

    private void Create_line()
    {
        RowDefinition gridRow = new RowDefinition();
        gridRow.Height = new GridLength(1, GridUnitType.Star);
        beGrid.RowDefinitions.Add(gridRow);
        StackPanel stack = new StackPanel();
        stack.Orientation = Orientation.Horizontal;
        TextBlock textBlock = new TextBlock();
        textBlock.Text = "Question";
        textBlock.Name = "Test" + i.ToString();
        RegisterName(textBlock.Name, textBlock);
        stack.Children.Add(textBlock);
        beGrid.Children.Add(stack);
        Grid.SetRow(stack, i);
    }

获取创建的 TextBlock:var text = (TextBlock)FindName("Test"+i.ToString());

您可以将所有创建的 StackPanel 存储在一个列表中。

private void AddLineButton_Click(object sender, RoutedEventArgs e)
{
    Create_line();
}

List<StackPanel> items;

private void Create_line()
{
    RowDefinition gridRow = new RowDefinition();
    gridRow.Height = new GridLength(1, GridUnitType.Star);
    beGrid.RowDefinitions.Add(gridRow);

    StackPanel stack = new StackPanel();
    stack.Orientation = Orientation.Horizontal;

    int i = items.Count + 1;
    TextBlock textBlock = new TextBlock();
    textBlock.Text = "Question";
    textBlock.Name = "Test" + i.ToString();

    stack.Children.Add(textBlock);
    beGrid.Children.Add(stack);
    Grid.SetRow(stack, items.Count);

    items.Add(stack);
}

您可以通过索引访问任何 previos 面板,例如items[0],并从 Children 属性 获取元素:items[0].Children[0] as TextBlock

像这样手动创建控件真的不是 WPF 的方式...

最好的方法是定义一个项目 class,其中包含您要显示/编辑的每个值的属性。

然后在 Window 中创建这些项目的 ObservableCollection(因为您将在单击按钮时手动添加项目),并将其设置为 ItemsSource 属性 ItemsControl 控件。 DataTemplate 用于定义显示控件内每个项目的确切控件,它将绑定到项目的属性。