【问题标题】:Add elements from XAML to grid defined in code behind [closed]将 XAML 中的元素添加到后面代码中定义的网格 [关闭]
【发布时间】:2021-02-05 14:44:00
【问题描述】:

我根据用户输入生成行和列,但我在后面的代码中执行此操作。但后来我想使用 XAML 添加按钮或文本块等元素。有什么建议?或者有什么方法可以使用 XAML 生成行和列?

Grid grid = new Grid();
grid.ShowGridLines = true;
for (int i = 0; i < 5; i++)
{
      ColumnDefinition column = new ColumnDefinition();
      RowDefinition row = new RowDefinition();
      grid.RowDefinitions.Add(row);
      grid.ColumnDefinitions.Add(column);
}
this.Content = grid;

然后我想添加一个这样的按钮:

<Button Grid.Column="3" Grid.Row="1">

</Button>

【问题讨论】:

标签: c# wpf xaml code-behind


【解决方案1】:

您还需要定义Grid 以将Button 添加到XAML 中。否则你会在哪里定义 Button 元素?

在 XAML 标记中给 Grid 一个 x:Name

<Window...>
    <Grid x:Name="root">
        <Button Grid.Column="3" Grid.Row="1">

        </Button>
    </Grid>
</Window>

...然后当您向其中添加行和列时,在代码隐藏中通过此名称引用它:

root.ShowGridLines = true;
for (int i = 0; i < 5; i++)
{
    ColumnDefinition column = new ColumnDefinition();
    RowDefinition row = new RowDefinition();
    root.RowDefinitions.Add(row);
    root.ColumnDefinitions.Add(column);
}

请注意,您不应在生成行和列的代码隐藏中创建另一个Grid 或设置视图的Content

【讨论】:

  • 谢谢,成功了!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-15
  • 1970-01-01
  • 2012-08-25
相关资源
最近更新 更多