我刚刚开始一个新的 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());